Search code examples
javaandroidevent-bus

How to use EventBus in Activity and Fragment on Android


In my application i want use EventBus for call some methods in another activities.
I want when click on backButton in activity (DetailActivity), call one method in fragment (MainFragment).
in MainFragment i have recyclerView and open this activity (DetailActivity) with recyclerView adapter.

I write below codes in DetailActivity and MainFragment but when click on backButton, not call method in MainFragment.

MainFragment codes :

public void onStart() {
    EventBus.getDefault().register(this);
    super.onStart();
}

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

@Subscribe(threadMode = ThreadMode.MAIN)
public void onRefreshAuctions(EventUpdateAuctionsState event){
    Toast.makeText(context, "OK", Toast.LENGTH_SHORT).show();
}

DetailActivity codes :

@Override
public void onBackPressed() {
    finishWithAnimate();
    EventBus.getDefault().post(new EventUpdateAuctionsState());
}

EventUpdateAuctionsState codes :

public class EventUpdateAuctionsState {
    public EventUpdateAuctionsState() {
    }
}

Why not call method in MainFragment?
How can i fix it?


Solution

  • Perhaps your Fragment is in stopped state when event is fired. Try to register, unregister in create/destroy lifecycle.

    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    

    Suggestion

    By the way why are you using EventBus for just backpress implementation. You can simply do this. If you fragment is child of DetailActivity.

    @Override
    public void onBackPressed() {
        finishWithAnimate();
        // get your fragment
        if(fragment!=null) fragment.onRefreshAuctions();
    }
    

    You can use getFragmentManager().findFragmentByTag("tag") if you don't have fragment instance.