DoubleP90
DoubleP90

Reputation: 1249

Run code over and over

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.

Upvotes: 0

Views: 1772

Answers (2)

4ndro1d
4ndro1d

Reputation: 2976

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);
    }
};

Upvotes: 3

Tuna Karakasoglu
Tuna Karakasoglu

Reputation: 1267

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);
}
};

Upvotes: 4

Related Questions