jublikon
jublikon

Reputation: 3447

EventBus event between two fragments not fired

Problem: I am using EventBus by greenrobot to pass some events. It is working for me unfortunately for the scenario of passing data between two fragments it does not. So the event does not get fired.

Question: Do I misunderstand the concept? Or is there a mistake in my code?

Note: Both Fragments exist at the time of sending the event. One fragment is the parent and the other one the child to display details.

detail fragment:

public class DetailFragment extends Fragment {
(...)

refreshButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
EventBus.getDefault().post(new IntentRefresh());
            }
        });
(...)

}

EventBus class:

public class IntentRefresh {

    public IntentRefresh (){}

    public void refreshParent() {

    }

}

parent fragment:

public class ParentFragment extends Fragment {

    (...)

    @Override
    public void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateList(IntentRefresh intentRefresh) {
        Toast.makeText(getActivity(), "LUEEEEPT", Toast.LENGTH_SHORT).show();
    }

    (...)
}

Upvotes: 0

Views: 1666

Answers (2)

Shohel Rana
Shohel Rana

Reputation: 2342

I use @CaseyB's answer. its working for me perfectly.Like below

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (!EventBus.getDefault().isRegistered(this))
        EventBus.getDefault().register(this);
}

@Override
public void onDetach() {
    super.onDetach();
    EventBus.getDefault().unregister(this);
}

@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(CallbackModel event) {

}

Upvotes: 0

CaseyB
CaseyB

Reputation: 25060

The Fragment lifecycle is quite a bit more complicated than the Activity lifecycle. I would guess that your onResume() isn't being called how you think it is. I would recommend moving your registering and un registering to the onAttach() and onDetach() methods.

Upvotes: 6

Related Questions