2

I want the toast message to display(if clicked on the right answer), but not go to the next activity directly. So i want to set a timer for like 2 seconds so the user can easily read it, and then go to the next activity. What is wrong with this code?

public void rightAnsnextQ (View view)  
{  
    Intent intent = new Intent(this, ThirdQuestion.class);


    Toast.makeText(this, "Good job", Toast.LENGTH_SHORT).show();  

    Thread.sleep(2000);

    startActivity(intent);

}
Y_Lakdime
  • 825
  • 2
  • 15
  • 33

3 Answers3

3

You are calling sleep on the ui thread which is wrong. It blocks the ui thread. You should never block the ui thread.

 Thread.sleep(2000); // remove this

Instead use Handler postDelayed with a delay of 2 seconds

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
 public void run() {
     // do something
     Intent intent = new Intent(ActivityName.this, ThirdQuestion.class);
     // If you just use this that is not a valid context. Use ActivityName.this
     startActivity(intent);
   }
}, 2000);
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
2

try below code:-

private final int interval = 1000; // 1 Second
private Handler handler = new Handler();
Private Runnable runnable = new Runnable(){
    public void run() {
        Toast.makeText(MyActivity.this, "C'Mom no hands!", Toast.LENGTH_SHORT).show();
    }
};


handler.postAtTime(runnable, System.currentTimeMillis()+interval);
handler.postDelayed(runnable, interval);

see below link for more info:-

How to set a timer in android

Community
  • 1
  • 1
duggu
  • 37,851
  • 12
  • 116
  • 113
0

try this,

  public void rightAnsnextQ (View view)  {

       Toast.makeText(this, "Good job", Toast.LENGTH_SHORT).show();  


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

          @Override
         public void run() {

        Intent intent = new Intent(this, ThirdQuestion.class);
                startActivity(intent);



            }

           }, 100);
  }
Akash Moradiya
  • 3,318
  • 1
  • 14
  • 19