3

What i am doing ::

  • I load a fragment(eg:: Fragment-A) to the container, and in onSaveInstanceState event i am storing some data into bundle

i use the code

@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putInt("yourSpinner", spnSearchByCity.getSelectedItemPosition());

    }
  • Now i replace the container with Fragment-B on click of button in Fragment-A

i use the code

fragment = FrgMdMap.newInstance(messengerObj);

                    if (fragment != null) {
                        getFragmentManager().beginTransaction().replace(R.id.content_frame, fragment).addToBackStack(null).commit();
                    }
  • I am successfully able to load the Fragment-B

  • Now on orientation change of Fragment-B the onSaveInstanceState of Fragment-A id firing


Questions::

  • How is this taking place ?
  • How can i make sure this wont happen ?
Devrath
  • 42,072
  • 54
  • 195
  • 297
  • Take a look : http://stackoverflow.com/questions/15608709/using-onsaveinstancestate-with-fragments-in-backstack – Arash GM Jul 21 '14 at 05:54

1 Answers1

4
How is this taking place ?

Actually Fragment-A is still alive and well underneath your Fragment-B that is due to the addToBackStack(null) added when you replaced the fragment.

How can i make sure this wont happen ?

You can remove the addToBackStack(null) or count the number of stacked fragments in your onSaveInstanceState method and when it is 0 then you can run the code inside your onSaveInstanceState

EDIT:

public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    FragmentManager fm = getActivity().getSupportFragmentManager();
    if(fm.getBackStackEntryCount() == 0)
    outState.putInt("yourSpinner", spnSearchByCity.getSelectedItemPosition());

}
Rod_Algonquin
  • 26,074
  • 6
  • 52
  • 63
  • [+1] for info .... on Quote"count the number of stacked fragments in your onSaveInstanceState method and when it is 0 then you can run the code inside your onSaveInstanceState" ...... Can you show me an example on your answer ! – Devrath Jul 21 '14 at 06:01
  • @Devrath first thing first are you only using the addtobackstack in your FragmentB – Rod_Algonquin Jul 21 '14 at 06:03
  • i am using addtobackstack in your FragmentA ... Not in B .... also i removed addToBackStack(null) in fragmentA ...still it is throwing same scenario(it might be holding any other thing in backstack ? possibly ?) ..... i was not able to understand " count the number of stacked fragments in your onSaveInstanceState method and when it is 0 then you can run the code inside your onSaveInstanceState" in the answer – Devrath Jul 21 '14 at 06:09
  • @ Rod_Algonquin .... I was able to resolve it thanks, but i want to ask ..... does the control always goes to previous fragment onsaveinstancestate when we rotate the device when we are in current fragment ? – Devrath Jul 21 '14 at 06:39