Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fragment does not respond to UI updates and eventbus events after resume

I have a SearchFragment class which extends a class called BaseFragment in which onResume and onStop are overridden as below:

@Override
public void onResume() {
  checkEventBusRegistration();
    super.onResume();
}
@Override
public void onStop() {
    EventBus.getDefault().unregister(this);
    super.onStop();
}
public void checkEventBusRegistration()
{
    if(!EventBus.getDefault().isRegistered(this))
    {
        EventBus.getDefault().register(this);
    }
}

SearchFragment is a fragment that shows a list of search results. By clicking each item, detail of product is shown on other fragment by below call:

getFragmentManager().beginTransaction().replace(R.id.container, new ProductDetailFragment()).addToBackStack(null).commit();

In addition some other events in my fragment do not work well. My fragment has a listView which does not respond to notifyDataSetChanged().

After returning back from ProductDetailFragment, eventbus subscriber are not triggered and some of events such as notifyDataSetChanged belonging to adapter of my listview do not respond and reflect changes on UI.

Debugging lines of code, after returning back from ProductDetailFragment, when control reaches to SearchFragment.onResume eventbus is still registered and it does not require registration again but generated events do not trigger subscribers.

In case it helps, here thre are the lifecycle events fired by my fragment:

Life cycle events on creating fragment:

onAttach
onCreate
onCreateView
onViewCreated
onViewCreated
onStart
onResume
onCreateOptionsMenu
onPrepareOptionsMenu

Life cycle events when leaving this fragment by replacing it:

onPause
onStop
onDestroyView
onDestroyOptionsMenu

Life cycle events when returning back to this fragment:

onCreateView
onViewCreated
onViewCreated
onStart
onResume
onCreateOptionsMenu
onPrepareOptionsMenu
like image 647
VSB Avatar asked Mar 11 '19 09:03

VSB


1 Answers

You can see that you onStop() is called when the fragment is replaced so the EventBus unregistered:

Life cycle events when leaving this fragment by replacing it:

onPause
onStop
onDestroyView
onDestroyOptionsMenu

And then, when you back to the fragment, your onResume() is called then EventBus is registered:

Life cycle events when returning back to this fragment:

onCreateView
onViewCreated
onViewCreated
onStart
onResume
onCreateOptionsMenu
onPrepareOptionsMenu

But when you returning back from ProductDetailFragment your fragment onResume() is not yet called. Hence the subscribe method in the fragment is not called.

like image 83
ישו אוהב אותך Avatar answered Oct 05 '22 01:10

ישו אוהב אותך