Friday, June 1, 2012

Android Multithreading: Updating the UI In Callback From Another Thread

Let's say for example, you have an asynchronous task making a network request, which will return the result to you in a callback.

The callback will be run in a separate thread, and is unable to update the UI, as Android does not allow other threads to update the UI (only the UI thread can).

The solution is to run the UI updating code inside the "runOnUiThread" method. In the following example, when the callback returns, the progressDialog is closed.

public void onRequestCompleted(String result) {
       runOnUiThread(new Runnable() {
         @Override
           public void run() {
          progressDialog.dismiss();
         }
       });
}

No comments:

Post a Comment