Question

I'm programming an Android app that teaches simple math. When a user enters a correct answer and presses a button, a message is displayed indicating whether they are correct. When an answer is correct, I want the message displayed for a few seconds and then the activity reloads.

This code correctly displays the message:

if (answer == userAnswer){          
resultsDisplay.setText(correctResponses[new 
       Random.nextInt(correctResponses.length)]);
}

else if (answer != userAnswer){
resultsDisplay.setText(incorrectResponses[new 
        Random().nextInt(incorrectResponses.length)]);
}

When I add a Thread.sleep, the text of resultsDisplay is either never set or set and removed so quickly that I don't see it happening. loadActivity() is a method I used to abstract the onCreate method, it works in every other case, so it isn't the problem. The thread does sleep before calling loadActivity, I just want the resultsDisplay text to display during that sleep:

if (answer == userAnswer){          
resultsDisplay.setText(correctResponses[new  
       Random.nextInt(correctResponses.length)]);

    try {
    Thread.sleep(5000);
    loadActivity(operand);
    } 
    catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
}

else if (answer != userAnswer){
resultsDisplay.setText(incorrectResponses[new 
        Random().nextInt(incorrectResponses.length)]);
}
Was it helpful?

Solution

Call sleep() in AsyncTask as currently you are sleeping UI thread and that's not good.

Blueprint for your asynctask should look like:

class YourAsync extends AsyncTask{

      onPreExecute(){
        // show message here
      }

      doInBackground(){
       // sleep here
      }

      onPostExecute(){
       // remove/reset message (whatever your requirement is )
       // loadActivity
     }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top