Reputation: 1887
I've got an activity with a retained fragment. This fragment handles DB queries and sends the results back to the activity via an interface.
When I rotate the device, the activity is destroyed and re-creates itself as expected. It also re-connects to the retained fragment (which wasn't destroyed) which is continuing to handle the DB queries despite the device rotation.
My problem is when the retained fragment gets the DB queries result back, it tries to send these via the interface to the activity. But, if the device has been rotated, the activity could be in the destroyed state (and not yet re-created) so the fragment can't send the results to the activity.
When the activity is eventually re-created, it's missed "it's chance" to receive the interface calls from the fragment and get the DB results. How to solve this?
Just a bit more detail - the activity has a button which the user presses to start the retained fragment doing the DB queries (they don't just start automatically when the activity is created or the activity attached to the fragment).
Activity.onCreate()
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
// Get our Retained Fragment if already exists, otherwise create a new one
FragmentManager fragManager = getSupportFragmentManager();
mRetFrag = (QueryFragment) fragManager.findFragmentByTag(QueryFragment.FRAGMENT_TAG);
if (mRetFrag == null) {
// First time - create a new retained fragment
mRetFrag = QueryFragment.newInstance();
fragManager.beginTransaction().add(mRetFrag, QueryFragment.FRAGMENT_TAG).commit();
}
// Button to start DB querying in fragment
Button queryBtn = (Button) findViewById(R.id.query_button);
queryBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mRetFrag.runDBQueries();
}
});
}
And in the fragment when it has the DB query results, I try to send this back to the Activity. So, mCallbackListener could be null if the activity isn't yet created.
// Pass the data to the activity
if (mCallbackListener != null) {
mCallbackListener.onQueryFinished(data);
}
Upvotes: 0
Views: 57
Reputation: 62189
Your mCallbackListener
points to an activity, which doesn't exist anymore, as long as it has been destroyed after rotation.
You have to get another instance of your activity:
if(null == mCallbackListener) {
mCallbackListener = (MainActivity) getActivity();
}
Another solution is to use event bus like Greenrobot's EventBus or Otto.
Here's nice blog about how to use Otto.
Upvotes: 1