Updating UI from another thread in Android

This problem that has give me quite a few headaches ( and i know i’m not the only one). Android will not let your touch the ui outside of the main thread. Apparently if you did you’d be breaking the second rule of the single-threaded model which is “do not access the Android UI toolkit from outside the UI thread“, as stated here http://developer.android.com/guide/components/processes-and-threads.html.

A solution to this (also stated in the same link) is to use Activity.runOnUiThread(Runnable) or View.post(Runnable). I had the task of loading images in a gallery. The problem for me was that the more images that were in the gallery was the longer it took to load. Naturally the solution to this is to load the images on a separate thread, adding a new image to the gallery after it’s loaded. I did this with a AsyncTask. Sure this seemed simple to do since i was using an a Adapter. I thought i could just add the newly loaded image to the list of images and the grid would automatically be updated. I was wrong. In order to update the grid holding the images i had to invalidate the adapter like this:

adapter.notifyDataSetChanged();

which, unfortunately, cannot be done outside the main UI thread.

So the solution is to post a Runnable to the grid’s event queue that would be executed whenever the grid’s events are being processed.


grid.post(new Runnable()
{
public void run()
{
adapter.notifyDataSetChanged();
}
});

Then changed it to this (both works, but this one is a bit more self explanatory)


GalleryActivity.this.runOnUiThread(new Runnable()
{
public void run()
{
adapter.notifyDataSetChanged();
}
});

The only difference between the two functions is that View.post adds the Runnable to the view’s even queue while Activity.runOnUiThread adds it to the Activity’s event queue.

enjoy

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s