Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

savedInstanceState when restoring fragment from back stack

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?

like image 299
heero Avatar asked Jun 20 '12 01:06

heero


People also ask

How can I maintain fragment state when added to the back stack?

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.

How do you save a fragment in savedInstanceState?

Here is an example: @Override protected void onCreate(Bundle savedInstanceState) { super. onCreate(savedInstanceState); if (savedInstanceState == null) { myFragment = MyFragment. newInstance(); getSupportFragmentManager() .

When should I call onSaveInstanceState?

Note that onSaveInstanceState() is called when your activity goes into the background and NOT when the app process is about to be killed.


1 Answers

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?

like image 117
Eric Avatar answered Oct 09 '22 04:10

Eric