Search code examples
androidtextviewscheduledexecutorserviceandroid-runonuithread

TextView setText not working inside ScheduledExecutorService runOnUiThread


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 ??


Solution

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