Cirrith
Cirrith

Reputation: 82

Wait in android

I am working on an Android project and I need to have the program wait for 5 seconds to display a message and then move on. I have looked around and I tried the Thread sleep(mili); but it didn't work so... I included my code and am I just doing something wrong or what else can I do?.

...
text.setText("You picked a goat");
lose++;
loser.setText("You have picked a goat " + lose + " time(s)");

Thread time = new Thread()
{
        @Override
        public void run(){
            try {
                synchronized(this){
                    wait(5000);
                }
            }
            catch(InterruptedException ex){}           
        }
    };

    time.start();

...

I also tried putting this in its own method and having it be called. The lose is just a counter and the "text" and "loser" are just textviews

Upvotes: 2

Views: 2209

Answers (1)

wsanville
wsanville

Reputation: 37516

One way to do this is to use the Handler class, which will allow you to call a Runnable after a given number of milliseconds. This is useful for short timespans, like in your case.

For example, using the postDelayed() method:

new Handler().postDelayed(new Runnable()
{
    @Override
    public void run()
    {
        //do your stuff here.
    }
}, 5000);

Upvotes: 5

Related Questions