David B.B.
David B.B.

Reputation: 15

sleep in android doesn't work

Well I just want to press a button and a countdown appears in it however when I press the button the program stops and finally shows the number 1 but doesn't show 3 or 2.

btnTurno.setOnClickListener(new View.OnClickListener() 
{
    public void onClick(View v) {
        btnTurno.setText("3");
        SystemClock.sleep(1000);
        btnTurno.setText("2");
        SystemClock.sleep(1000);
        btnTurno.setText("1");
    }
});

What I'm doing wrong?

Upvotes: 0

Views: 1458

Answers (3)

fadden
fadden

Reputation: 52303

Setting the text and drawing the text are separate operations that both happen on the same thread. You're setting the text three times before the framework gets the chance to draw anything, so all you see is the last change.

For this to work, you'd need to do your text updates and sleeps on a separate thread. However, you can't make UI calls directly on a different thread, so you need to post your messages.

One approach would be to create an AsyncTask, and use your code above but call publishProgress() where you're currently calling setText(). The publishProgress() call in the async thread results in onProgressUpdate() running in the UI thread; from there, you can call setText() to update the UI.

Edit: the CountDownTimer approach mentioned in a different answer is better.

Upvotes: 1

FOliveira
FOliveira

Reputation: 556

First of all, Sleep should be called as Thread.sleep(x);

But on the other hand , sleep is NOT recommended since it will block the user interaction with the application.

If you want to make a countdown ( as it looks like what you are doing ), you should look at this http://developer.android.com/reference/android/os/CountDownTimer.html

Upvotes: 3

marcinj
marcinj

Reputation: 49976

onClick is being executed in single handler message on GUI thread, so each time you change text, it overwrites previous value, so system is not able to redraw view.

Also you should not call sleep() on main gui thread, that will cause ANR - application is notresponding

Upvotes: 1

Related Questions