Reputation: 2258
Code :
private void startTimer() {
final ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(1);
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
int count = 60;
time.setText(count - 1 + "");
count--;
}
});
}
}, 0 , 1000, TimeUnit.MILLISECONDS);
}
I want to update text in TextView for every 1 second, but this seems to work only for the first time and later text is not updated.
Anyone know what's the issue ??
Upvotes: 1
Views: 936
Reputation: 75798
Read How to run a Runnable thread in Android
You can use Handler
A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.
You need to use handler.postDelayed(new Runnable()
method .
Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses. The runnable will be run on the thread to which this handler is attached .
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
// Add your code Here
handler.postDelayed(this, 1000); // You can change your time
}
}, 900);
Upvotes: 2
Reputation: 1386
int count = 60;
private void startTimer() {
final ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(1);
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
if(count > 0){
time.setText(count - 1 + "");
count--;
}
}
});
}
}, 0 , 1000, TimeUnit.MILLISECONDS);
}
Upvotes: 5