Countdowntimer cancel crashes the app when click on button - android

I am trying to create a countDownTimer but, whenever I click on the button the app crashes.
I want that if I click on player1 button player2 countdown should pause and vice versa for player2.
The Error I am getting:
Attempt to invoke virtual method 'void
android.os.CountDownTimer.cancel()' on a null object reference
Here is the Code
public class Timer extends AppCompatActivity {
Button player1, player2;
long incrementTime = 3000;
int time;
long timeinLong;
ImageButton pause;
CountDownTimer player1count, player2count;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
player1 = findViewById(R.id.player1);
player2 = findViewById(R.id.player2);
Intent intent = getIntent();
time = intent.getIntExtra("time", 0);
timeinLong = time * 60000;
int minutes = (int) (timeinLong / 1000) / 60;
int seconds = (int) (timeinLong / 1000) % 60;
String timeFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
player1.setText(timeFormatted);
player1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startCountDown(player1);
player2count.cancel();
}
});
player2.setText(timeFormatted);
player2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startCountDown2(player2);
player1count.cancel();
}
});
}
private void startCountDown(final Button button) {
player1count = new CountDownTimer(timeinLong, 1000) {
#Override
public void onTick(long millisUntilFinished) {
timeinLong = millisUntilFinished;
updateCountDownText(button);
}
#Override
public void onFinish() {
timeinLong = 0;
updateCountDownText(button);
}
}.start();
}
private void startCountDown2(final Button button) {
player2count = new CountDownTimer(timeinLong, 1000) {
#Override
public void onTick(long millisUntilFinished) {
timeinLong = millisUntilFinished;
updateCountDownText(button);
}
#Override
public void onFinish() {
timeinLong = 0;
updateCountDownText(button);
}
}.start();
}
private void updateCountDownText(Button button) {
int minutes = (int) (timeinLong / 1000) / 60;
int seconds = (int) (timeinLong / 1000) % 60;
String timeFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
button.setText(timeFormatted);
if (timeinLong < 30000) {
button.setTextColor(Color.RED);
} else {
button.setTextColor(Color.BLACK);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (player1count != null) {
player1count.cancel();
}
}
}

player2count only gets initialized inside startCountDown2, which is only called inside player2.setOnClickListener. Hence, if you click on the player1 button before ever clicking on player2 button, you'll get a NullPointerException, since calling player2count.cancel() on a not-yet-initialized player2count is not allowed. To prevent this from happening, it would be appropriate to just check for null in this case:
if (player2count != null) {
player2count.cancel();
}

Just don't cancel timers unless they're intialized, it will bring NPE, so check if they're not null in both players as below
player1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startCountDown(player1);
if (player2count != null)
player2count.cancel();
}
});
player2.setText(timeFormatted);
player2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startCountDown2(player2);
if (player1count != null)
player1count.cancel();
}
});

you don't initialize that when click listener called
i fixed it for myself by add try catch on .cancel lines
or set
if (player1count != null)
...

Related

How to automatically add to a number when a CountDownTimer is running?

I am trying to add numbers to an already existing number based on a formula when a CountDownTimer is running. The timer is working, but the number(amount) crashes the app
public class Main extends AppCompatActivity {
TextView Time;
ImageButton button;
TextView amount;
TextView rate, milltime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Time = findViewById(R.id.Time);
button = findViewById(R.id.button);
amount = findViewById(R.id.Amount);
rate = findViewById(R.id.Ratenumber);
milltime = findViewById(R.id.milltime);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new CountDownTimer(10000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
NumberFormat f = new DecimalFormat("00");
long hour = (millisUntilFinished / 3600000) % 24;
long min = (millisUntilFinished / 60000) % 60;
long sec = (millisUntilFinished / 1000) % 60;
Time.setText(f.format(hour) + ":" + f.format(min) + ":" + f.format(sec));
}
#Override
public void onFinish() {
Time.setText("Click to start");
}
}.start();
new CountDownTimer(10000,1){
#Override
public void onTick(long millisUntilFinished) {
milltime.setText(""+millisUntilFinished /1000 + millisUntilFinished %1000);
}
#Override
public void onFinish() {
milltime.setText("Did it work?");
}
}.start();
int n1 = Integer.parseInt(milltime.getText().toString());
int n2 = Integer.parseInt(rate.getText().toString());
int n3 = (1000 - n1) * n2;
amount.setText(""+String.valueOf(n3));
}
});
}
What I am trying to get, is the amount to increase as the timer runs based on the rate.
without the xml I'm only assuming here
First of all, the calculation code is on the button click and out of the counter scope your crash might be because of the Integer parsing
where your milltime and rate could be empty and that's what making it crash due to NumberFormatException

Why does timer loop not initialize at initial value when it calls onFinish() method?

I want to build a 5 second timer that counts down to 0 in 1 second intervils and then resets to the initial value of 5 seconds. The timer needs to run continously. After looking at this thread,
Android - loop part of the code every 5 seconds
I used the CountDownTimer Class and called the start() method within the onFinish() method so that when the timer finished, it would reset to 5. It does run on a continous loop, however I notice that after the first loop, it either countsdown as 4-3-2-1-0 or 5-3-2-1-0.
Can somebody explain to me why this happens?
private long START_TIME_IN_MILLIS = 5000;
//set up our variables
private CountDownTimer timer;
private TextView textView;
private Button starttimer;
private long mTimeLeftInMillis = START_TIME_IN_MILLIS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text_view_countdown);
starttimer = findViewById(R.id.button_start_pause);
//set onclik listener when touch imput button
starttimer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
beginTime();
}
});
}
//creating my own method
private void beginTime() {
timer = new CountDownTimer(mTimeLeftInMillis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
mTimeLeftInMillis = millisUntilFinished;
updateCountDownText();
}
#Override
public void onFinish() {
start();
}
}.start();
}
private void updateCountDownText(){
int minutes= (int) (mTimeLeftInMillis / 1000)/ 60;
int seconds= (int) (mTimeLeftInMillis / 1000) % 60;
String timeLeftFormatted = String.format(Locale.getDefault(),"%02d:%02d", minutes, seconds);
textView.setText(timeLeftFormatted);
}
}
Try this
#Override
public void onFinish() {
mTimeLeftInMillis = START_TIME_IN_MILLIS;
}

countdowntimer with sound.is it possible?

I want to ask a question I have put the timer to count down from 10:00 min..I want it when it goes at 2 min to put a sound for 10 seconds like an error sound or alarm sound is that possible and if it is can I have some help plz??
Yes it's possible, all you have to do to check the remaining time and play the sound accordingly:
private static final int Two_Seconds = 120000;
public void startTimer(){
countDownTimer = new CountDownTimer(timeLeftInMilliseconds,10000) {
#Override
public void onTick(long millisUntilFinished) {
if(millisUntilFinished <= Two_Seconds){
// display your sound
}
timeLeftInMilliseconds = millisUntilFinished;
updateTimer();
}
#Override
public void onFinish() {
}
}.start();
countdownButton.setText("PAUSE");
timerRunning = true;
}
countdownText = findViewById(R.id.countdown_text);
countdownButton = findViewById(R.id.countdown_button);
countdownButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startstop();
}
});
updateTimer();
}
public void startstop(){
if(timerRunning){
stopTimer();
}else {
startTimer();
}
}
public void startTimer(){
countDownTimer = new CountDownTimer(timeLeftInMilliseconds,1000) {
#Override
public void onTick(long millisUntilFinished) {
timeLeftInMilliseconds = millisUntilFinished;
updateTimer();
}
#Override
public void onFinish() {
}
}.start();
countdownButton.setText("PAUSE");
timerRunning = true;
}
public void stopTimer (){
countDownTimer.cancel();
countdownButton.setText("START");
timerRunning = false;
}
public void updateTimer (){
int minutes = (int) timeLeftInMilliseconds / 60000;
int seconds = (int) timeLeftInMilliseconds % 60000 / 1000;
String timeLeftText;
timeLeftText = "" + minutes;
timeLeftText += ":";
if(seconds <7)timeLeftText +=0;
timeLeftText += seconds;
countdownText.setText(timeLeftText);
}
}

Countdown timer with pause and resume

I want to do countdown timer with pause and restart.Now i am displaying countdown timer By implenting ontick() and onfinish().please help me out.HEre is th code for countdown timer
final CountDownTimer Counter1 = new CountDownTimer(timervalue1 , 1000)
{
public void onTick(long millisUntilFinished)
{
System.out.println("onTick method!"(String.valueOf(millisUntilFinished/1000)));long s1=millisUntilFinished;
}
public void onFinish()
{
System.out.println("Finished!");
}
}
in onTick method..save the milliseconds left
long s1=millisUntilFinished;
when you want to pause the timer use..
Counter.cancel();
when you want to resume create a new countdowntimer with left milliseconds..
timervalue=s1
counter= new Counter1();
counter.start();
See this link
I would add something to the onTick handler to save the progress of the timer in your class (number of milliseconds left).
In the onPause() method for the activity call cancel() on the timer.
In the onResume() method for the activity create a new timer with the saved number of milliseconds left.
Refer the below links
LINK
LINK
My first answer on stackOverFlow, hope it should help :) ...
This is how I solved the problem, control timer from Fragment, Bottomsheet, Service, Dialog as per your requirement, keep a static boolean variable to control.
declare in your Activity:
long presetTime, runningTime;
Handler mHandler =new Handler();
Runnable countDownRunnable;
Toast toastObj;
public static boolean shouldTimerRun = true;
TextView counterTv;
In onCreate:
presetTime =60000L;
runningTime= presetTime;
//setting up Timer
countDownRunnable=new Runnable() {
#Override
public void run() {
if (shouldTimerRun) //if false, it runs but skips counting
{
counterTv.setText(simplifyTimeInMillis(runningTime));
if (runningTime==0) {
deployToast("Task Completed"); //show toast on task completion
}
runningTime -= 1000;
presetTime = runningTime; //to resume the timer from last position
}
mHandler.postDelayed(countDownRunnable,1000); //simulating on-tick
}
};
mHandler.post(countDownRunnable); // Start our CountdownTimer
Now, whenever you want to pause the timer change the value of shouldTimerRun false and to resume make it true.
#Override
public void onResume() {
super.onResume();
shouldTimerRun=true;
}
#Override
public void onPause() {
super.onPause();
shouldTimerRun=false;
deployToast("Timer is paused !!");
}
Helping methods: (can be skipped)
public static String simplifyTimeInMillis(long time) {
String result="";
long difference = time;
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
if (difference<1000){
return "0";
}
if (difference>=3600000) {
result = result + String.valueOf(difference / hoursInMilli) + "hr ";
difference = difference % hoursInMilli;
}
if (difference>=60000) {
result = result + String.valueOf(difference / minutesInMilli) + "m ";
difference = difference % minutesInMilli;
}
if (difference>=1000){
result = result + String.valueOf(difference / secondsInMilli) + "s";
}
return result;
}
public void deployToast(String msg){
if (toastObj!=null)
toastObj.cancel();
toastObj = Toast.makeText(mContext,msg,Toast.LENGTH_SHORT);
toastObj.show();
}
I'm using two private vars in this case:
private long startPauseTime;
private long pauseTime = 0L;
public void pause() {
startPauseTime = System.currentTimeMillis();
}
public void resumen(){
pauseTime += System.currentTimeMillis() - startPauseTime;
}
I am afraid that it is not possible to pause or stop CountDownTimer and pausing or stopping in onTick has no effect whatsoever user TimerTask instead.
Set up the TimerTask
class UpdateTimeTask extends TimerTask {
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
timeLabel.setText(String.format("%d:%02d", minutes, seconds));
}
}
if(startTime == 0L) {
startTime = evt.getWhen();
timer = new Timer();
timer.schedule(new UpdateTimeTask(), 100, 200);
}
You can add event listener's like this..
private Handler mHandler = new Handler();
...
OnClickListener mStartListener = new OnClickListener() {
public void onClick(View v) {
if (mStartTime == 0L) {
mStartTime = System.currentTimeMillis();
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(mUpdateTimeTask, 100);
}
}
};
OnClickListener mStopListener = new OnClickListener() {
public void onClick(View v) {
mHandler.removeCallbacks(mUpdateTimeTask);
}
};
For more refer to Android Documentation.
//This timer will show min:sec format and can be paused and resumed
public class YourClass extends Activity{
TextView timer;
CountDownTimer ct;
long c = 150000; // 2min:30sec Timer
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.YourXmlLayout);
timer = (TextView)findViewById(R.id.Yourtimer)
startTimer(); // it will start the timer
}
public void startTimer(){
ct = new CountDownTimer(c,1000) {
#Override
public void onTick(long millisUntilFinished) {
// Code to show the timer in min:sec form
// Here timer is a TextView so
timer.setText(""+String.format("%02d:%02d",millisUntilFinished/60000,(millisUntilFinished/1000)%60));
c = millisUntilFinished; // it will store millisLeft
}
#Override
public void onFinish() {
//your code here
}
};
ct.start();
}
/*===========================================================
*after creating this you can pause this by typing ct.cancel()
*and resume by typing startTimer()*/
public class MainActivity extends AppCompatActivity {
TextView textView;
CountDownTimer ctimer;
boolean runCountDown;
private long leftTime;
private static final long MILL_IN_FUTURE = 6000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text_view);
textView.setText("Click to start");
textView.setOnClickListener(this::clickStartAndPauseAndResume);
leftTime = MILL_IN_FUTURE;
}
public void clickStartAndPauseAndResume(View view) {
if (!runCountDown) {
long time = (leftTime == 0 || leftTime == MILL_IN_FUTURE) ? MILL_IN_FUTURE : leftTime;
ctimer = new CountDownTimer(time, 1) {
#Override
public void onTick(long l) {
leftTime = l;
textView.setText(l + "ms");
}
#Override
public void onFinish() {
textView.setText("Done");
leftTime = 0;
runCountDown = false;
textView.postDelayed(new Runnable() {
#Override
public void run() {
textView.setText("Click to start");
}
}, 1000);
}
}.start();
runCountDown = true;
} else {
ctimer.cancel();
textView.setText(textView.getText() + "\n Click to resume");
runCountDown = false;
}
}
}
A nice and simple way to create a Pause/Resume for your CountDownTimer is to create a separate method for your timer start, pause and resume as follows:
public void timerStart(long timeLengthMilli) {
timer = new CountDownTimer(timeLengthMilli, 1000) {
#Override
public void onTick(long milliTillFinish) {
milliLeft=milliTillFinish;
min = (milliTillFinish/(1000*60));
sec = ((milliTillFinish/1000)-min*60);
clock.setText(Long.toString(min)+":"+Long.toString(sec));
Log.i("Tick", "Tock");
}
The timerStart has a long parameter as it will be reused by the resume() method below. Remember to store your milliTillFinished (above as milliLeft) so that you may send it through in your resume() method. Pause and resume methods below respectively:
public void timerPause() {
timer.cancel();
}
private void timerResume() {
Log.i("min", Long.toString(min));
Log.i("Sec", Long.toString(sec));
timerStart(milliLeft);
}
Here is the code for the button FYI:
startPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(startPause.getText().equals("Start")){
Log.i("Started", startPause.getText().toString());
startPause.setText("Pause");
timerStart(15*1000);
} else if (startPause.getText().equals("Pause")){
Log.i("Paused", startPause.getText().toString());
startPause.setText("Resume");
timerPause();
} else if (startPause.getText().equals("Resume")){
startPause.setText("Pause");
timerResume();
}

CountDownTimer issue

Basically my aim is to have this timer reset whenever the user presses button b. I've tried a few methods such as if( i==true && bIsPressed()) but no luck, any ideas?
//2 buttons
Button =b;
TextView = time;
//countdown code
CountDownTimer Count = new CountDownTimer(11000, 1000) {
public void onTick(long millisUntilFinished) {
time.setText(""+millisUntilFinished / 1000);
}
public void onFinish() {
time.setText("Finished");
}
}; Count.start();
Haven't tested it, but I would do something along the lines of:
private void setupTimerResetButton()
{
mTimerResetButton.setOnClickListener(new OnClickListener(){
public void onClick(){
resetTimer();
}
});
}
private void resetTimer()
{
if(mTimer != null){
mTimer.cancel();
mTimer = null;
}
mTimer = new CountDownTimer(11000, 1000) {
public void onTick(long millisUntilFinished) {
mTimerTextView.setText(""+millisUntilFinished / 1000);
}
public void onFinish() {
mTimerTextView.setText("Finished");
}
};
mTimer.start();
}

Categories

Resources