problem to reset CountDownTimer

0

I'm setting up a project to learn and I can not find a solution for a timer, let's say time has already been selected 10 minutes and the user wants to change to 5 minutes by clicking 5 min should cancel the old time and start the new but I can not implement this, 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();
}
    
asked by anonymous 16.06.2017 / 20:36

1 answer

0

I think you're forgetting to set TIMER to null when you call TIMER.cancel(); . Since you're using the fact that TIMER is null or not as flag.

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

This 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();
    }
    
17.06.2017 / 19:13