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.

5
  • 3
    "Does not work" is never a sufficient problem description. stackoverflow.com/questions/how-to-ask
    – Matt Ball
    Jul 30, 2012 at 16:03
  • what does not works? do you get any errors?
    – 0gravity
    Jul 30, 2012 at 16:04
  • Have you tried looping the clock() call instead of the executeClock()?
    – November
    Jul 30, 2012 at 16:05
  • How about using a timer and updating your UI every second or more often if you want to .. ? Inspiration: stackoverflow.com/a/6702767/1525300.
    – wojciii
    Jul 30, 2012 at 16:18
  • 1
    Your while loop is too fast for the UI to update. Use a Handler.
    – slybloty
    Jul 30, 2012 at 16:24

2 Answers 2

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);
}
};
2
  • 1
    Wouldn't that call it a way too often? You have to make an if statement instead of your while.
    – 4ndro1d
    Jul 30, 2012 at 16:12
  • 1
    now it seems quite right :) but I'm not sure if the @Override is missing at the run method
    – 4ndro1d
    Jul 30, 2012 at 16:18
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);
    }
};
1
  • 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, 2012 at 17:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.