0

In my application I am showing a clock in a TextView, and I want to update it in real time. I tried to run it like this:

public void clock() {
    while(clock_on == true) {
        executeClock();
    }
}

public void executeClock() {
    TextView timeTv = (TextView) findViewById(R.id.time);
    long currentTime=System.currentTimeMillis();
    Calendar cal=Calendar.getInstance();
    cal.setTimeInMillis(currentTime);
    String showTime=String.format("%1$tI:%1$tM %1$Tp",cal);
    timeTv.setText(showTime);
}

But it doesn't work.

Codemwnci
  • 54,176
  • 10
  • 96
  • 129
DoubleP90
  • 1,249
  • 1
  • 16
  • 29

2 Answers2

4

Please Try:

private Handler handler = new Handler();
runnable.run();

private Runnable runnable = new Runnable() 
{

public void run() 
{
     //
     // Do the stuff
     //
     if(clock_on == true) {

             executeClock();

     }

     handler.postDelayed(this, 1000);
}
};
Tuna Karakasoglu
  • 1,262
  • 9
  • 28
3

Use a Handler:

private Handler handler = new Handler() {

    @Override
    public void handleMessage(android.os.Message msg) {
            TextView timeTv = (TextView) findViewById(R.id.time);
            long currentTime=System.currentTimeMillis();
            Calendar cal=Calendar.getInstance();
            cal.setTimeInMillis(currentTime);
            String showTime=String.format("%1$tI:%1$tM %1$Tp",cal);
            timeTv.setText(showTime);

            handler.sendEmptyMessageDelayed(0, 1000);
    }
};
4ndro1d
  • 2,926
  • 7
  • 35
  • 65
  • 1
    This. Not only you need a handler to be able to update the textview (handlers run in UI thread) from anywhere, you can also use it to run delayed code... so instead of getting stuck in a while loop forever, simply call your clock update every 500-1000ms. – Shark Jul 30 '12 at 17:40