Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How & where to use setInitialSavedState & saveFragmentInstanceState inside Fragments

I'm trying to create a Fragment that retains its state after it is shown back.

For this I tried using getFragmentManager().saveFragmentInstanceState() inside onPause() & then calling setInitialSavedState() inside onCreateView().

Issues I'm facing is I dont know how to use them exactly and when to call them.

Also both functions take a paramater of type SavedState, which I'm not sure how to use.

Code:

public class AudioContainerFragmentClass extends Fragment implements
        OnClickListener {

    final String TAG = "AudioContainerFragmentClass";
    private Button bSetName;
    private TextView tvName;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = null;
        try {
            Log.e(TAG, "onCreateView()");
            view = inflater.inflate(R.layout.audio_fragment_container, null);
            bSetName = (Button) view.findViewById(R.id.bSetName);
            tvName = (TextView) view.findViewById(R.id.tvName);
            bSetName.setOnClickListener(this);

            if(savedInstanceState != null){
                setInitialSavedState(/* WHICH SavedState OBJECT TO PASS */);
            }
            Log.e(TAG, "onCreate()");

        } catch (Exception e) {
            Log.e(TAG, "onCreateView(): " + e.toString());
        }
        return view;
    }

    /*
    @Override
    public void onSaveInstanceState(Bundle outState) {
        Log.e(TAG, "onSaveInstanceState()");
        super.onSaveInstanceState(outState);
    }
    */

    @Override
    public void onClick(View v) {
        tvName.setText("sometext");
    }

    @Override
    public void onPause() {
        super.onPause();
        getFragmentManager().saveFragmentInstanceState( /* WHAT TO ADD HERE */);

    }

}
like image 847
reiley Avatar asked Feb 16 '23 00:02

reiley


1 Answers

Just investigating this myself and thought I'd record what I found.

setInitialSavedState() can't be called after a Fragment has been attached to an Activity, as noted in the Android source code around line 491.

setInitialSavedState() is intended to be used immediately after instantiating fragments in code. For example:

AudioContainerFragmentClass newFrag = new AudioContainerFragmentClass();
newFrag.setInitialSavedstate(savedStateObject);
like image 115
joates Avatar answered May 21 '23 07:05

joates