Thursday, May 31, 2012

Using View.post() - Update the UI From a Background Thread

There are a number of ways of updating the UI from a background thread, including using AsyncTask, using a Handler, or simply by calling View.post().  This article will cover the easiest of the 3 approaches which is using View.post()

View.post() accepts a Runnable and as per the javadoc

Causes the Runnable to be added to the message queue. The runnable will be run on the user interface thread.
This method can be invoked from outside of the UI thread only when this View is attached to a window.

The use case for this might be something like this.  You have a UI element that you want to be updated periodically and you have a custom Thread that you have created for doing the background work (perhaps managed in the onStart() and onFinish() of the Activity/Fragment lifecycle).  To update the UI, you MUST be on the UI thread, and the easiest way for this to happen is to call post() on a known view.
parentView.post(new Runnable() {
     public void run() {
         performUIUpdate();
     }
});
The above example assumes the parentView is a view reference that you have obtained in the onCreate() and the performUIUpdate() is a method that you have created that will do the UI update.

Again, in many cases, The AsyncTask or Handler is a better choice for this.  But, it's good know that IF you are not using one of those 2 solutions, then this is a very simple way to update the UI and ensure that your update happens on the UI thread.

Wednesday, May 30, 2012

Welcome

Hello Fellow Android Developers,

Welcome to the Android Developer Tips blog.  This is a blog about actively developing in Android, and I'll try to post some useful design patterns and code samples as I solve many little issues related to Android development.

I have published a couple Apps to Google Play, and I have many more that yet uncompleted.  As a Java developer with 15+ years of Java experience I love working in Android.  But, things are not always rosy in Android Land.  There are days that feel like throwing in the towel because I spent way to long trying to figure out dynamically load an Image from a URL, or why a ListView of images was always showing the same image, etc.  Over time, I'll hopefully build up a nice little chest of Android tips that other developers may find useful as well.