0

I have a fragment that contains a spinner and I need to re-use the fragment across two activities so that the selection status of the spinner persists.

I have used the suggestion from this SO answer to implement saveFragmentInstanceState() and setInitialSavedState() in the following manner:

  1. On activity A, the user selects a spinner item
  2. saveFragmentInstanceState() is called on activity A's spinnerFragment
  3. Activity B is then started
  4. setInitialSavedState() is called on activity B's spinnerFragment
  5. Activity B should be shown with the same selected spinner value as before...

...but this doesn't happen as, in activity B, the selected spinner value is not remembered.

My code is below. Can anyone see what the problem might be? Or am I not using the correct approach?

SpinnerFragment - code executed when a spinner item is selected...

Intent activityBIntent = new Intent(getActivity(), ActivityB.class);
android.app.FragmentManager fm = getActivity().getFragmentManager();
SavedState spinnerFragmentState = fm.saveFragmentInstanceState(SpinnerFragment.this);
activityBIntent.putExtra(ActivityB.FRAGMENT_STATE_KEY, spinnerFragmentState);
startActivity(activityBIntent);

Activity B - code executed in onCreate()...

    setContentView(R.layout.activity_b);

    /*
     * Create fragmentContainer
     */
    SpinnerFragment spinnerFragment = new SpinnerFragment();
    SavedState spinnerFragmentState = getIntent().getParcelableExtra(FRAGMENT_STATE_KEY);
    Log.d(LOG_TAG, "spinnerFragmentState: " + spinnerFragmentState); //this isn't null
    spinnerFragment.setInitialSavedState(spinnerFragmentState);

    /*
     * Add spinnerFragmentContainer to layout
     */
    android.app.FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.add(R.id.spinnerFragmentContainer, spinnerFragment);
    fragmentTransaction.commit();

PS - Unlike this question, the other questions/answers I have found on this topic do not refer to persisting fragment state between different activities.

Community
  • 1
  • 1
ban-geoengineering
  • 18,324
  • 27
  • 171
  • 253
  • I haven't used this method but according to documentation `saveFragmentInstanceState ` saves fragment's current instance state, so probably fragment's `onSaveInstanceState` is called. I think you should store spinner's current selection in that callback and try to restore it when new fragment with this state is created.. – Gennadii Saprykin Aug 02 '15 at 15:42
  • Thanks, but that hasn't worked. If that was the route, I may as well have just passed the selection int value anyway. – ban-geoengineering Aug 02 '15 at 17:48

0 Answers0