Nejsem Nikdo
Nejsem Nikdo

Reputation: 11

I have an error in a thread making time "run" (update every second)

Here is my code:

public void run() {
        try {
            while (!isInterrupted()) {
                Thread.sleep(1000);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
            }
        } catch (InterruptedException e) {
        }
    }
};
thread.start();

The Thread is called Thread and I want to display the time in a TextView called TextView. There is some error in the Threadbecause even though the time displays in the TextView, it does not update every second. Thanks

Upvotes: 0

Views: 87

Answers (2)

Matias Olocco
Matias Olocco

Reputation: 509

As stated, you should use Handler with Runnable, here is an example with your code:

final Handler handler = new Handler();
final Runnable task = new Runnable() {
    @Override
    public void run() {
        //Your code
        handler.postDelayed(this, 1000);
    }
};
handler.postDelayed(task, 1000);

More info about Handlers, in the doc.

Upvotes: 2

Ali Faris
Ali Faris

Reputation: 18592

use Runnable And Handler

Runnable runnable = new Runnable() {
    @Override
    public void run() {

        Date time = Calendar.getInstance().getTime();
        textView.setText(DateFormat.format("hh:mm", time));

        handler.postDelayed(this, 1000);
    }
};

Handler handler = new Handler();
handler.post(runnable);

Upvotes: 2

Related Questions