Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onSaveInstanceState of previous fragment is called on-orientation of current fragment

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 ?
like image 668
Devrath Avatar asked Jan 29 '26 18:01

Devrath


1 Answers

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());

}
like image 103
Rod_Algonquin Avatar answered Jan 31 '26 08:01

Rod_Algonquin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!