Reputation: 2465
Have a question regarding the savedInstanceState bundle that you get on the fragment's callbacks when the fragment is first created and then reattached to the activity.
So I use the setRetainInstance(true), as a result the fragment shouldn't be destroyed but just unattached from the activity when the activity is destroyed and then reattached back when the activity is recreated on a configuration change for example.
So, because using this setRetainInstance(true) this will cause the savedInstanceState bundle to ALWAYS be null in the fragment's callbacks such as: onActivityCreated()
, onCreate()
etc.
So far so good, now I'm getting some crashes from some users (a really really small number) which is caused by this savedInstanceState not being null on the fragment.
So, the onActivityCreated() callback is doing something like this:
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
adapter = new CustomAdapter(getActivity(), getListView(), data, savedInstanceState);
setListAdapter(adapter);
setupEmptyListView();
getListView().setOnScrollListener(this);
}
The CustomAdapter is calling at some point from its constructor a loadInstanceState()
method which does its job, code below:
@Override
public void loadInstanceState(Bundle savedInstanceState) {
if (savedInstanceState != null) {
//do some stuff which is causing a crash
}
}
Now my question is how is it possible to get into that if statement when the savedInstanceState that I'm passing should always null.
And now the QUESTION:
Is Android guaranteeing THAT WHEN USING setRetainInstance(true)
on a fragment the savedInstanceState bundle which is passed to the callbacks will ALWAYS be null?
Thanks for answers guys!
Upvotes: 3
Views: 7543
Reputation: 6343
I didn't find any mention that savedInstanceState bundle must be null in this case. The official documentation says:
public void setRetainInstance (boolean retain)
Control whether a fragment instance is retained across Activity re-creation (such as from a configuration change). This can only be used with fragments not in the back stack. If set, the fragment lifecycle will be slightly different when an activity is recreated:
onDestroy() will not be called (but onDetach() still will be, because the fragment is being detached from its current activity).
onCreate(Bundle) will not be called since the fragment is not being re-created.
onAttach(Activity) and onActivityCreated(Bundle) will still be called.
IMHO that's main difference - changed lifecycle.
Upvotes: 1