0

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

K.Os
  • 5,123
  • 8
  • 40
  • 95

2 Answers2

2

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.

Matias Olocco
  • 509
  • 4
  • 9
2

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);
Ali Faris
  • 17,754
  • 10
  • 45
  • 70
  • Check that he starts sleeping the thread, so the first post should be delayed as well. – Matias Olocco Aug 10 '17 at 11:38
  • I think he do that to make the task execute every second , not that he want to make it delay – Ali Faris Aug 10 '17 at 11:40
  • 1
    Yes, of course, but he could put the sleep after the execution of his code, putting it at the begining is just to delay the first execution as well (maybe he is putting some data in the TextView already?, who knows...). But then again, maybe it is just a mistake. Just an observation. – Matias Olocco Aug 10 '17 at 11:42