I'm new to android and pretty new to the concept of timing in Java also. I've tried to create a simple app that counts the number of user clicks on the screen in five seconds. After the time ends, I want to disable the button and restart everything when clicking the 'Restart' button.
This is the current code:
public void clickCounter(View view){
++counter;
if(showCounter!=null)
showCounter.setText(Integer.toString(counter));
}
public void clickTimer(final View view) {
final Button Tap = findViewById(R.id.Tap);
clickCounter(view);
new CountDownTimer(5000, 5000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
Tap.setEnabled(false);
}
}.start();
}
public void restartCounter(View view) {
counter=0;
showCounter.setText("Tap");
final Button Tap = findViewById(R.id.Tap);
Tap.setEnabled(true);
}
The button does disable after 5 seconds, but the restart button sometimes enables and then disables it right away (the counter and text changes properly).
I think the problem might be the way I'm using the Timer to do it (maybe I should use threads?)
You are creating a new timer on every button tap. So, when you reenable the button, one of your timers could be expiring, disabling the button afterwards. You should only create a new timer if there is none running.