Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 409
Seatter Avatar asked Oct 01 '22 06:10

Seatter


1 Answers

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);
like image 171
Raghunandan Avatar answered Oct 05 '22 11:10

Raghunandan