Reputation: 11
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 Thread
because even though the time displays in the TextView
, it does not update every second. Thanks
Upvotes: 0
Views: 87
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
Reputation: 18592
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