Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event Bus in Fragment

I have created one Activity (DemoActivity.java) with 2 Fragments (FragmentOne.java and FragmentTwo.java).

I registered the EventBus in the Activity like thisEventBus.getDefault().register(this);

and created one Suscriber method in the Activity:

@Subscriber
public void abc(String str) {
    Log.i(TAG,"MainActivity Called !!");
}

Then I post an event from FragmentTwo.java on button click EventBus.getDefault().post("");

This scenario works fine for me. But when I create the same subscriber method in FragmentOne.java it is not working. Why?

like image 745
sanil Avatar asked Mar 10 '17 07:03

sanil


People also ask

What is purpose of event Bus?

EventBus is an open-source library for Android and Java using the publisher/subscriber pattern for loose coupling. EventBus enables central communication to decoupled classes with just a few lines of code – simplifying the code, removing dependencies, and speeding up app development.

How does Java event bus work?

EventBus is a software bus that allows you to register certain events and get notified when something related to that event is published. Events are in the form of classes. First, you register your class to the bus and then define methods that use the Subscribe annotation in order to register to an event.


1 Answers

From your question there might be two things that are causing the issue:

  1. You might have not registered the EventBus in your FragmentOne class like you did for your DemoActivity class.
  2. If you have registered the EventBus in the FragmentOne class then please check if FragmentOne fragment class is alive and in state to receive the event while posting the event from FragmentTwo class.

Edit

As seen from comments you have registered your EventBus as EventBus.getDefault().register(getActivity()) due to this only your Activity will get registered. To register your Fragment use EventBus.getDefault().register(this) in your Fragment.onCreate() method.

like image 141
Nitin Joshi Avatar answered Sep 20 '22 17:09

Nitin Joshi