problem to reset Countdowntimer

Asked

Viewed 53 times

0

I’m putting together a project to learn and I can’t find a solution for a timer, let’s say that time has already been selected 10 minutes and the user wants to change to 5 minutes when clicking 5 min should cancel the old time and start the new but I can’t implement it, follows the code :

if (TIMER != null) {
  TIMER.cancel();
  display.setText("00:00");
} else if (TIMER == null) {
  TIMER = new CountDownTimer(300000, 1000) {
    public void onTick(long millisUntilFinished) {
      display.setText("Tempo restante: " + millisUntilFinished / 1000);
    }
    public void onFinish() {
      display.setText("00:00");
      pausarMusica();
    }
  }.start();
}

1 answer

0


I think you’re forgetting to set the TIMER to null when you call the TIMER.cancel();. Since you’re wearing the suit of TIMER was null or not as a flag.

After the first run, according to your code, it will never be null again, so it will never fall in the second if.

That should work:

if (TIMER != null) {
      TIMER.cancel();
      TIMER = null;
      display.setText("00:00");
    } else if (TIMER == null) {
      TIMER = new CountDownTimer(300000, 1000) {
        public void onTick(long millisUntilFinished) {
          display.setText("Tempo restante: " + millisUntilFinished / 1000);
        }
        public void onFinish() {
          display.setText("00:00");
          pausarMusica();
        }
      }.start();
    }
  • 1

    So, I thought well as I was not even falling in the second if and the code runs from top to bottom I simply removed the If and left the rest of the code out, it worked! thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.