Updating frequently a TextView inside a loop

The problem
How to update a TextView inside a loop or, more generally, how to update frequently an UI element of an Activity.
See the following example:

  1. create an Android project without a starting activity
  2. edit the file AndroidManifest.xml
  3. edit the the file res/layout/activity_main.xml
  4. create the file eu/lucazanini/updateui/MainActivity.java

The expected result is that to update frequently the TextView for 5 seconds displaying the device time, instead the observed result is that of a single update at the end.

The cause
In the LogCat you can see the message “Skipped […] frames! The application may be doing too much work on its main thread.”; the message is clear: too many operation on the main thread also known as UI thread.
A first attempt to solve the problem may be to call the updateUI method from another thread as in the following example:

but the application crashes at the line 45 launching the exception “android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.”.
In fact, you can’t access a View from threads other than the main one.
So the question is how to access a View without taking up too many resources from the UI thread?

The first solution: the Handler class
An instance of a Handler is associated with the thread in which it was created, in this case the main thread, and a second thread (separateThread) uses the Handler to send a Message to the main thread.

The second solution: the AsyncTask class
In this example, the inner class MyAsyncTask extends the abstract class AsyncTask, and overwrites the doInBackground method that performs the calculation and with the line publishProgress calls the onProgressUpdate method that performs the updating of the TextView.
Often the update of the TextView is required after it has been completed the doInBackground method, in this case, you can insert the code to update the TextView in the OnPostExecute method.

2 Comments

 Add your comment
  1. This worked for me! Thank you!

  2. I am curios to know if this code works. I am running something very similar but I am getting the error “Only the original thread that created a view hierarchy can touch its views”. After reading many posts I have seen people usually set views on the UI thread instead of on the async task and use async tasks to run other time consuming code.

Leave a Comment

Your email address will not be published.