3

Problem

onSaveInstanceState is being called on device rotation for a fragment which has been replaced in a fragment transaction. This is causing an IllegalStateException with the message "Content view not yet created.

Research

I have found the following two answers which seem most relevant

Using onSaveInstanceState with fragments in backstack?

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

What I've tried already

Following the answer to the second question I have removed addtobackstack from the fragment transaction but am still getting the error.

I read the accepted answer to the first question but am not sure how to get a fragment reference within onSaveInstanceState for the activity. I also don't particularly want to save that fragment, when the user leaves that fragment it's state does not need to be saved.

I have also tried adding if (getView() != null) {...} to the onSaveInstanceState in the fragment but this made no difference.

Questions

  1. Why is onSaveInstanceState being called even though the fragment hasn't been added to the back stack?
  2. Is the right approach to somehow kill the fragment when the user is done with it?
  3. Is there a different solution?

Thank you in advance for your help.

Andrew

Edit

If I remove addtobackstack(null) from the transaction which adds the fragment and the one where it is removed the problem goes away, but then so does an important piece of functionality... I could add that case to my onBackPressed override function but it seems a bit of a hack, and not in a good way.

Community
  • 1
  • 1
user1977132
  • 487
  • 2
  • 18

1 Answers1

1

Adding an isVisible() check onSaveInstanceState of the fragment in the backstack should work.

No need to retain instance state when it is not visible.

isolator
  • 36
  • 4