0

I have a android fragment hosted in an activity. The activity is not overriding any onsaveInstanceState or onRestoreInstanceState methods. in my fragment i put the following code:

  @Override
    public void onDestroy() {
        super.onDestroy();
        Bundle b = new Bundle();
        b.putParcelable("mymodel", myModel);
        onSaveInstanceState(b);
    }

when user hits the back button i see this being called (i know its not guaranteed for ondestroy to be called, thats not my point). so i put a break point and indeed this code gets called. Then i return to the activity and it opens the fragment but the savedInstanceState is null in oncreate and in onViewCreated. What am i doing wrong ? i thought i could call this manually to save state ?

j2emanue
  • 60,549
  • 65
  • 286
  • 456
  • Please check this post for saving instance state https://stackoverflow.com/questions/151777/saving-android-activity-state-using-save-instance-state?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Kaung Khant Thu May 28 '18 at 05:30

2 Answers2

1

No you cannot call onSaveInstanceState manually. The framework does that for you. Calling that will only update your bundle, not the framework bundle. The proper way is to override it and save your data.

tompee
  • 1,408
  • 1
  • 7
  • 6
  • yes i see what you mean. instead what i have done is converted the model to json string and serialized it to shared prefs. when i want to restore it i deserialize it from sharedprefs. – j2emanue May 28 '18 at 07:16
1

You should not call onSaveInstanceState manually, it is Android Framework's job to do that whenever it is necessary.

If you want to save information and retrieve it later, just override onSaveInstanceState and put your info in the bundle.

Adib Faramarzi
  • 3,798
  • 3
  • 29
  • 44