Can I use savedInstanceState()
to save the state when removing a fragment, then restore the state when I pop the fragment off the back stack? When I restore the fragment from the back stack, savedInstanceState bundle is always null.
Right now, the app flow is: fragment created -> fragment removed (added to back stack) -> fragment restored from back stack (savedInstanceState bundle is null).
Here is the relevant code:
public void onActivityCreated(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle = getArguments(); Long playlistId = bundle.getLong(Constants.PLAYLIST_ID); int playlistItemId = bundle.getInt(Constants.PLAYLISTITEM_ID); if (savedInstanceState == null) { selectedVideoNumber = playlistItemId; } else { selectedVideoNumber = savedInstanceState.getInt("SELECTED_VIDEO"); } } public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(Constants.SELECTED_VIDEO, selectedVideoNumber); }
I think the problem is that onSavedInstanceState()
is never called when being removed and being added to back stack. If I cant use onsavedInstanceState(), is there another way to fix this?
add() - (create and) add a Fragment B and it overlap Fragment A, which is still active in the background. remove() - can be used to remove Fragment B and return to A. Fragment B will be recreated when called later on.
Here is an example: @Override protected void onCreate(Bundle savedInstanceState) { super. onCreate(savedInstanceState); if (savedInstanceState == null) { myFragment = MyFragment. newInstance(); getSupportFragmentManager() .
Note that onSaveInstanceState() is called when your activity goes into the background and NOT when the app process is about to be killed.
onSaveInstanceState is (unfortunately) not called in normal back-stack re-creation of a fragment. Check out http://developer.android.com/guide/components/fragments.html#Creating and the answer on How can I maintain fragment state when added to the back stack?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With