Search code examples
javaandroiduser-interfacesleep

Pause execution in Java GUI


I am writing a quiz program for the Android (written in Java). When the user answers a question (by clicking a button), I want to flash a message on the screen saying whether they were correct or not, followed by a 5 second pause before moving on to the next question.

However, when an answer button is clicked, the program pauses, but does not display the message of correct/incorrect. The message only comes up once the sleep method has finished.

if (correct)   
    Answer.setText("CORRECT!"); 
else 
    Answer.setText("WRONG!"); 

try { Thread.sleep(5000); } 
catch(InterruptedException e) {}

As a bonus, I'd like the answer buttons to be disabled during the pause.


Solution

  • Imo AsyncTask is too much for this usecase.

    Don't use sleep. Instead set your correct/incorrect message and than do this:

    new Handler().postDelayed(new Runnable(){
      public void run()
      {
        goToNextScreen();
      }
    }
    , 5000);