Skip to content
Advertisement

Why does my Timer crashes my android activity when I stop it?

I’m trying to make a toggle button that can stop and replay a Timer, it worked just fine until I added a new method called “Set_BPM”. It starts and it stops correctly, it crashes when I try to start it again after I stopped it.

This is the class where I’m using the Timer:

public class Metronome {

int miliseconds;
Timer timer = new Timer();

public Metronome () { }

public void Set_BPM (int bpm) {
    miliseconds = (60000 / bpm);
}

public void Start (final Context context) {
    TimerTask timerTask = new TimerTask () {
        @Override
        public void run() {
            Sonidos.Tick(context);
        }
    };
    timer.schedule(timerTask, 1000, miliseconds);
}
public void Stop () {
    timer.cancel();
    timer.purge();
}
}

And this is how I’m calling it:

public void Encender_Metronomo (View view) {
    if (tb_metronome.isChecked()) {
        metronome.Set_BPM(Integer.parseInt(et_bpm.getText().toString()));
        metronome.Start(this);
    }
    else
        metronome.Stop();

    Sonidos.Button(this);
}

There’s also this object on top of my Activity:

private Metronome metronome = new Metronome();

This is what Logcat says

Advertisement

Answer

Once you cancel() a Timer, you cannot schedule more tasks with it. Quoting the documentation:

Once a timer has been terminated, its execution thread terminates gracefully, and no more tasks may be scheduled on it.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement