Whenever it’s needed to perform some heavy/slow task on a mobile application, it’s a good practice to perform that specific operation on the background, using a thread.
So far so good, but sometimes it’s necessary to update the UI from this background thread. If you ever tried to access an UI element from a background thread, you have already noticed that an exception is thrown.
Let’s assume that the method “doSomeHardWork()” does something really heavy and that the method “updateUI()” updates the interface.
Let’s see how can we update the interface from the background thread:
Upgrade your computer with an SSD
public class YourClass extends Activity { private Button myButton; //create an handler private final Handler myHandler = new Handler(); final Runnable updateRunnable = new Runnable() { public void run() { //call the activity method that updates the UI updateUI(); } }; private void updateUI() { // ... update the UI } private void doSomeHardWork() { //.... hard work //update the UI using the handler and the runnable myHandler.post(updateRunnable); } private OnClickListener buttonListener = new OnClickListener() { public void onClick(View v) { new Thread(new Runnable() { doSomeHardWork(); }).start(); } }; }
That’s it. The post method of the Handler allows the runnable to access the UI.
Try it out
Thanks, but how to update UI on background??? Because according to your code, the updateUI() thread still freezes the screen during the updating process.
How are you calling the method?
I really want to thank you for this tutorial it really helped me and i did finish my assignment i am really grateful
You save two people butt….Thanks alot.!!!!!
Works perfectly. Best post about that issue out of like 150 I checked!
Brilliant! No other post across the internet on handlers that I’ve come across is as clear as yours. Thank you.
Thanks, very helpful – saved me lots of time.
有難うございました。。。:-)
おかげ様で、background threadでUIを更新する事ができました。
Thank you. . . It is
Thanks to, I was able to update the UI in the background thread.
Hi
Just one thing: The handler constructor by default runs on the background thread. So your method updateUI() is still on the background thread so i doubt it if it has access to UI.
Using the getMainLooper() inside the Handler constructor can make the handler run on the UI thread.
Great article! Succinct and to the point. Very useful in sorting out the problems I had. Thanks very much for posting this even though it was a couple of years ago now!
G
It’s working but i dont know why my activity keep crashing after few second updating another view.
I try to change form view using custom LinearLayout class.
No exception or error.
But my activity keep going to onDestroy method.
Please help
Can you create a a gist(https://gist.github.com/) with your code?
Are you creating a Toast notification in your code, from the the backgroun thread?