Search code examples
javaandroid

Java android EventBus No subscribers registered for event class


In activity I do this:

onCreate():

EventBus.getDefault().register(this);

and I override this:

@Override
protected void onStart() {
  super.onStart();
  EventBus.getDefault().register(this);
}

@Override
protected void onStop() {
  EventBus.getDefault().unregister(this);
  super.onStop();
}

And in my service I did this:

Global.getInstance().getGeoLocation().setBestLocation(loc);
EventBus.getDefault().post(new EventLocation(loc));

And in logsd I see this:

10-27 09:15:04.367 5097-5097/komunal W/EventBus: Subscriber to unregister was not registered before: class komunal.activities.PGOListActivity
10-27 09:15:04.458 5097-5097/komunal D/EventBus: No subscribers registered for event class komunal.events.EventLocation
10-27 09:15:04.458 5097-5097/komunal D/EventBus: No subscribers registered for event class org.greenrobot.eventbus.NoSubscriberEvent
10-27 09:15:05.425 5097-5097/komunal D/EventBus: No subscribers registered for event class komunal.events.EventLocation
10-27 09:15:05.425 5097-5097 komunal D/EventBus: No subscribers registered for event class org.greenrobot.eventbus.NoSubscriberEvent
10-27 09:15:06.458 5097-5097/komunal D/EventBus: No subscribers registered for event class komunal.events.EventLocation
10-27 09:15:06.459 5097-5097/komunal D/EventBus: No subscribers registered for event class org.greenrobot.eventbus.NoSubscriberEvent
10-27 09:15:07.435 5097-5097/komunal D/EventBus: No subscribers registered for event class komunal.events.EventLocation
10-27 09:15:07.436 5097-5097/komunal D/EventBus: No subscribers registered for event class org.greenrobot.eventbus.NoSubscriberEvent

Solution

  • First, you need to only register the subscriber once. So, if you've already registered in onCreate don't register it again in onStart().

    Second, whenever your activity is no longer visible, you're activity will be unsubscribed from the event. This is because you have the following:

    @Override
    protected void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }
    

    Instead, you need to move the unregistering to the onDestroy():

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
    

    Last, you need to subscribe to the Event in your activity with something like this:

    // process the event in the Main thread.
    @Subscribe(threadMode = ThreadMode.MAIN) 
    public void onMessageEvent(EventLocation event) {
      // do something with the event.
    }