user2966161
user2966161

Reputation:

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);
}

Upvotes: 4

Views: 5218

Answers (2)

Bikesh M
Bikesh M

Reputation: 8373

new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {

          //your code here
          //you can add a block of code or a function cll

          //myFunction();

        }
    }, 1000);  //setting 1 second delay : 1000 = 1 second

I fount this sample from here http://wiki.workassis.com/android-execute-code-after-10-seconds

Upvotes: 0

Raghunandan
Raghunandan

Reputation: 133560

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);

Upvotes: 3

Related Questions