Having trouble with EventBus

In the 1st fragment I send a post

EventBus.getDefault().post(new TestString("123")); 

In the 2nd fragment I register the EventBus (in the onStart method)

 EventBus.getDefault().register(this); 

And I define a method for reading the passed parameters (in the 2nd fragment)

 @Subscribe public void onEvent(TestString event){ tx4.setText(event.getS()); } 

In response, I receive:

D / EventBus: No customers registered for event class com.example.user_android.a366.Model.TestString

D / EventBus: No subscribers for event class or.g.greenrobot.eventbus.NoSubscriberEvent

  • Where is register called? And is unregister ? Both fragments are created and are in the same activation? I would add logs before registering in order to make sure that it is invoked. - lllyct
  • register is called in the 2nd fragment method (which accepts data) onStart () - Heaven
  • unregister is called in the onDestroy method (the 2nd fragment it accepts) - Heaven
  • Both fragments are in the same activity and the transition between them is carried out using replace - Heaven

1 answer 1

You send from one fragment, and you want to get the event in another, not yet created at the time of sending. It does not work out. If you want to transfer data to the fragment being created, use setArguments when creating the fragment. And if you want to receive events via EventBus, then subscribers should be subscribed before sending an event. More precisely, only those signed at the time of dispatch will receive events, and this is the essence. And I would use a pair of methods for subscribing and unsubscribing, for example, onStart and onStop . And better onResume and onPause .

  • That is, for a subscription, I have to specify something like EventBus.getDefault (). Register (ListFragment.class); - Heaven
  • No, I mean that in your case the subscription is not suitable because the fragments are displayed at different times. In theory, this mechanism was created in order to transfer events from one part of the application to another, but existing simultaneously with the source of the event. And to transfer data to the created fragment, you must use setArguments , because when you throw an event, this fragment does not exist, and certainly it has not yet called onStart, where you register the event listener. - lllyct
  • Got it, thank you - Heaven