Search code examples
androidlistviewtimertask

Android: Periodically change the Text of a TextView of a Custom ListView


In a Custom ListView i have a TextView whose Text must change periodically every 1 min, to the Current Time and Date.

So i did this:

Timer mTimer = new Timer();
mTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {

currentTime = System.currentTimeMillis();
(holder.myText).setText(new Date(currentTime));
}
}, 0, 60000);

in the getView of the Custom Adapter.

It works for the First time, because getView is called when setting the Adapter for the 1st time.

Next time it gives Exception:

android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

so where exactly should i use this code?

If my practice itself is bad, please give me an idea how to achieve this.

Thank You


Solution

  • You can't update a UI object from a Thread that is not the UI Thread. Try this:

    this.runOnUiThread(new Runnable(){
       @Override
       public void run(){
           //update your TextView here
       }   
    })