Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling and Mitigating IllegalStateException ("failure saving state: active $Fragment has cleared index: -1")

My Android application manages multiple fragments. I am seeing a large number of crashes in the field, however, containing this log line:

java.lang.IllegalStateException: Failure saving state: active XxxFragment{81e598 id=0x7f0b0069 tag_yyy} has cleared index: -1

Searches of answers in Stack Overflow have been fruitless; I seem to have a lot of company in wondering exactly what this exception means. Digging into the exception trace and Android sources, I can see that the exception is coming from the point at which my main Activity is saving its state (FragmentActivity.onSaveInstanceState), and the individual Fragments are being written into a Parcelable. Each Fragment has an index (called mIndex) which must be nonnegative, but it's not really clear from the code why that must be the case, as mIndex is never used again in that function.

I have no good idea how the Fragment gets into this state, or what I can do about it. I have been unable to reproduce the error in my own test environment. Can anyone shed any light on how to avoid and/or deal with this exception?

Related SO questions:

java.lang.IllegalStateException: Failure saving state: active has cleared index in fragment

What does active fragment has cleared index: -1 mean and how do I fix it?

Getting exception as Failure saving state: active Fragment has cleared index: -1 when I am pressing home button of android device

IllegalStateException with Android Fragments

like image 658
Patrick Brennan Avatar asked Jan 29 '15 01:01

Patrick Brennan


1 Answers

I'm going to redact my previous comment and make this an actual answer. setRetainInstance(true) was a red herring. At least in my case. Start here: http://www.localwisdom.com/blog/2013/03/android-error-java-lang-illegalstateexception-failure-saving-state-active-fragmentname/

"You most likely tried to perform a fragment transaction where you didn’t have reference to the correct instance of a fragment"

When I read that it all made sense for me. I was doing 2 wrong things with fragments.

  1. My offending fragments were singletons. (Major no-no)
  2. I was trying to use these same fragment instances across Activities without correctly saving state. (Which can be achieved by methods mentioned here: https://stackoverflow.com/a/12465343/333525)

(Hope this helps. It was too long for just a comment.)

like image 94
prodaea Avatar answered Oct 15 '22 15:10

prodaea