0

Followed by a lot of searhcing and googling, i have tried various things to get onsaveState working when a user navigates to a different fragment and then go back into the previous fragment using the back key.

i have two fragments A and B that gets loaded and used in a container xml layout that is housed by a normal Activity. a Single Activty.

here is how i add a fragment into the fragment manager and into my container xml

FragmentA about = new FragmentA();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.mainViewContainer, about).addToBackStack(TAG_ABOUT_PAGE);
        ft.commit();

Here is the onsaveState on FragmentA

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
//save something
outState.putParcelable(KEY_CENTER_POINT, mlatLong);
Log.d("jjj", "onsaveInsanceState");

}

Fragment B gets called like this

  FragmentB fragmentB = new FragmentB();
            FragmentTransaction ft = fm.beginTransaction();
            ft.replace(R.id.mainViewContainer, fragmentB).addToBackStack(TAG_ABOUT_PAGE);
            ft.commit();

When the user presses the back key, the whole lifecycle of fragmentA gets called, onAttach, oncreate, oncreateView etc and the fragment gets displayed but the values not saved as it did not call onsaveInstanceState when the fragment was replaced by fragmentB.

any ideas?

i could hardcode and create a singleton representing the value i wish to store and just load it up from oncreateView but this is not ideal and is a last resort.

Thanks

Jono
  • 17,341
  • 48
  • 135
  • 217
  • 1
    Refer this http://stackoverflow.com/questions/15608709/using-onsaveinstancestate-with-fragments-in-backstack?answertab=votes#tab-top – droid kid Nov 04 '14 at 12:10
  • 1
    From my experience whatever value you saved in global variable of Fragment will not be lost during navigation. So, while coming back to the fragment you can check whether the values is there or not in onCreateView and do necessary actions. Also the initialization can be done in onAttach, as this is called only when fragment first attach to activity. – droid kid Nov 04 '14 at 12:28

0 Answers0