Seatter Seatter - 4 months ago 14
Java Question

Android: Implement a 1 second interval timer before calling a function

I am trying to introduce a 1 second pause before I reset the game (resetGame()). After a button has been pressed. bAnswer1 text does equal ansewrArray[0]. The App force closes after the 1 second delay set in newQuestionTimer().

import java.util.Timer;
import java.util.TimerTask;

Timer timer = new Timer();

bAnswer1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(bAnswer1.getText().toString().equals(answerArray[0]))
{
bAnswer1.setBackgroundColor(Color.GREEN);
newQuestionTimer();
}
else
{
bAnswer1.setBackgroundColor(Color.RED);
guess++;
}
}
});

public void newQuestionTimer()
{
timer.schedule(new TimerTask() {
@Override
public void run() {
resetGame();
}
}, 1000);
}

Answer

You are updating ui from a timer which runs on a background thread. Ui can be updated only on the ui thread.

You can use a Handler

   Handler handler = new Handler();
   handler.postDelayed(new Runnable(){
        @Override
        public void run() {
            bAnswer2.setBackgroundColor(Color.TRANSPARENT);           
            bAnswer3.setBackgroundColor(Color.TRANSPARENT);         
            bAnswer4.setBackgroundColor(Color.TRANSPARENT);
        }
    }, 1000);