0

I need to display a numbers(1-8) on single TextView like one by one and with sleeptime 1sec. here is my code

    for(int i=0;i<9;i++){
        TextView txt=(TextView)findViewById(R.id.txt);
        txt.setText(String.valueOf(i));
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
amalBit
  • 12,041
  • 6
  • 77
  • 94
sunil
  • 300
  • 3
  • 20

2 Answers2

3

Use a Handler or a CountDownTimer. Do not call sleep(param) on the ui thread. This blocks the ui thread. never block the ui thread.

Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

http://developer.android.com/reference/android/os/Handler.html

Regarding CountDownTimer

http://developer.android.com/reference/android/os/CountDownTimer.html

You can find example of both @

Android Thread for a timer

Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • is there any problem using this code. handler will run every minute, when we open the app. new Handler().postDelayed(new Runnable() { @Override public void run() { if(i<9){ TextView txt=(TextView)findViewById(R.id.txt); txt.setText(String.valueOf(i)); ++i; } handler(); } }, 100); – sunil Jun 13 '14 at 10:24
  • You can stop the `Handler` when you want to. – Raghunandan Jun 13 '14 at 10:25
  • @sunil there i have mentioned in the last link. Check that – Raghunandan Jun 13 '14 at 10:27
0

You can try using handler.

TextView txt=(TextView)findViewById(R.id.txt);
int i = 0;

Handler handler=new Handler();  

handler.post(runnable);  
Runnable runnable=new Runnable(){  
    @Override  
    public void run() {  
        txt.setText(String.valueOf(i));
        handler.postDelayed(runnable, 1000);  
        i++;
        if (i == 10)
        {
            handler.removeCallbacks(runnable);
        }
    }  
};  

Hope it helps.

MysticMagicϡ
  • 28,593
  • 16
  • 73
  • 124