Trying to use Thread.sleep to change the question after the toast is done

Hi,

I’ve just started going through your great book, and on the GeoQuiz app, I am trying to add in a little functionality so that the question changes automatically a little after the toast finishes. I’m trying to use the following code:

    private void checkAnswer(boolean userPressedTrue){
    int messageResID = (userPressedTrue==mQuestionBank[mCurrentIndex].isTrueQuestion()) ? R.string.correct_toast : R.string.incorrect_toast;
    Toast toast =Toast.makeText(QuizActivity.this,messageResID,Toast.LENGTH_SHORT);
    Thread thread=new Thread(){
        @Override
        public void run(){
            try{
                sleep(3000);
                QuizActivity.this.nextButton_click();
            }catch(Exception e){}
        }

    };
    toast.show();
    thread.start();
}

but I get weird results, either the question changes immediately, as though Thread.sleep returns straight away without sleeping, or the question doesn’t change at all but the app continues to respond, as though Thread.sleep threw an exception.

Unfortunately I haven’t read the debug chapter yet, so can’t debug it !

Does android do weird things with threads ?

Cheers,

Stuart

aha, I read on to logging in chapter 3, and it’s throwing this error:

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

hmm. I guess I need to make some kind of callback to the thread the QuizActivity listeners are running in.

I tried with a Timer and TimerTask as well and get same errors

You can only update the UI when you are on the main thread. Your code is updating on a different thread so you’re seeing strange behavior.

The best way to solve this problem is with a handler. You will learn much more about handlers in the HandlerThread chapter later in the book.

private void checkAnswer(boolean userPressedTrue){
    int messageResID = (userPressedTrue==mQuestionBank[mCurrentIndex].isTrueQuestion()) ? R.string.correct_toast : R.string.incorrect_toast;
    Toast toast =Toast.makeText(QuizActivity.this,messageResID,Toast.LENGTH_SHORT);
    toast.show();
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run(){
         ...
        }
    }, 3000);

}

thanks very much, will check that out