[Android] Changing UI from another thread with Handler

I think this is basic issue for the developing Android app. I didn’t know it, so this is the memo.

This is the story for Changing UI from another thread with Handler as the title.

CalledFromWrongThreadException error

As for the android app, the following error occurred if Ui is tried to changed by another thread.

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

Android app was considered to use single thread, and to change UI from other thread than main thread is forbidden.

However, we usually make other thread to execute some heavy process and we want to show the result in main display. This time, I also want to show the result of another thread in main display and I meet the upper error.

Use Handler

I searched the upper error by google, I found the solution soon. The solution is to use Handler.

First, Handler object is made in the main thread, for example, in the “onCreate”

@Override
protected void onCreate(Bundle savedInstanceState) {
        ︙
    Handler handler = new Handler();
        ︙
}

Change UI with handler in another thread.

new Thread(new Runnable() {
    @Override
    public void run() {
            ︙
        handler.post(new Runnable() {
            @Override
            public void run() {
                textView.setText("Thread Finished.");
            }
        });
    }
}).start();

That’s it.

References