Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EventBus posting can't update Toolbar Title. Any workaround?

I use EventBus (GreenRobot) to post from backgroundThread to my activity (which is a UiThread). I could start a fragment etc. I also want to update my Title, so I did as below. (calling the Activity setTitle())

@Subscribe
public void onEvent(AuthenticationEvent event) {
    setTitle(event.getTitle());
}

However, there's an error as below reported. (The App didn't crash, but the Error is clearly shown on the log, and the Toolbar title behave weird after that).

E/EventBus: Could not dispatch event: class package.AuthenticationEvent to subscribing class class package.MainActivity
      android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6357)

Is there a way I could workaround it, where the post from EventBus could still allow me to update my Ui (e.g. Title)?

like image 598
Elye Avatar asked Dec 01 '22 13:12

Elye


1 Answers

You can only update any UI components from the UI thread. If you try to update UI from background thread it will not work and may cause the app to crash.

By default @Subscribe method will be executed in the posting thread, which is your background thread. That is why your code doesn't work. To make it work, you have to use @Subscribe(threadMode = ThreadMode.MAIN) so that it will be executed in the UI thread. For your specific code:

// Called in Android UI's main thread
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(AuthenticationEvent event) {
    setTitle(event.getTitle());
}
like image 138
Chau Thai Avatar answered Dec 15 '22 15:12

Chau Thai