Run code on main/UI thread on android

Android’s UI components are not thread safe so one may need to update Views or other UI components from a secondary thread when returning from an asynchronous database query or a web service call.  If you run the code from a secondary thread you might see that the code crashes almost on each try.

Below you can find two methods on how can one run a code on the main/UI thread on android:

1. runOnUIThread Activity’s method

runOnUiThread(new Runnable(){
     public void run() {
          // UI code goes here
     }
});

2. Handler

Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
     public void run() {
          // UI code goes here
     }
});

As a note, you might want to use one of the two methods whenever you want to update the UI like setting a text on a TextView, updating colors on views or other UI related stuff. Otherwise, the application might crash because the UI classes on Android are not thread safe.

Exit mobile version