Android: Updating View from Background Thread

Issue:
 
For a small game application that I am currently working on, I needed to change the display text at certain intervals of time. Initially I tried to simply update the view(UI) using a timer class that runs after every 2 seconds. But I came across this error which says “Only the original thread that created a view hierarchy can touch its view.”
After some googling I came across a nice solution from Carlos Rodrigues site.
Basically, the solution involves creating a separate thread each time the update is required. The thread implements a Runnable interface to update the view which is executed using a Handler.

private final Handler myHandler = new Handler();

      
final Runnable updateRunnable = new Runnable() {
        public void run() {
            //call the activity method that updates the UI
              UpdateDisplayColor();
        }
       };
The thread which goes inside the onCreate method:
Thread thread = new Thread(new Runnable() {
                    
                     @Override
                     public void run() {
                           Timer t = new Timer();
                           t.scheduleAtFixedRate(
                                      new TimerTask()
                                      {
                                          public void run()
                                          {    
                                                doSomeHardWork();
                                          }
                                      },
                                      0,      // run first occurrence immediatetly
                                      2000); // run every two seconds     
                     }
              });
              thread.start();
 
And finally the implementation of the handler:
private void UpdateDisplayColor()
       {
              Random rand = new Random();
              index = rand.nextInt(4); //since there are only four colors         
              color = colors[index];
              TextView displayName= (TextView)findViewById(R.id.textView1);                           
       displayName.setText(color);             
       }
      
private void TimeToUpdateView()
    {        
        myHandler.post(updateRunnable);
        Log.d(“ColorName”,color);
    }
References:
http://crodrigues.com/updating-the-ui-from-a-background-thread-on-android/
http://developer.android.com/reference/android/os/Handler.html
Tags: