Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setRetainInstance not working for ListFragment when using compatibiltiy library

I'm attempting to save a ListFragment subclass across an orientation change so I added setRetainInstance(true) to the end of my onCreate function. I added an onSaveInstanceState method to add all of it's data to a bundle, then added code into onActivityCreated to load that data back. Unfortunately, it wouldn't work.

When I added some debugging messages with the help of Log.d I discovered that not only was onSaveInstanceState not being called, but onCreate was (which the documentation seems to say shouldn't happen when retainInstance is true). Neither onCreate nor onActivityCreated have bundles with my data (unsuprisingly).

I'm guessing this may be a problem with compatibility library, though I don't have an android 3.0+ device to test this.

Any help is appreciated and I can post some code snippets if necessary, though I'm not doing anything complicated.

Update: onDestroy is not being called when I change orientation (which is how it should be), so it seems that some of setRetainInstance is working

like image 224
rofer Avatar asked Aug 02 '11 01:08

rofer


2 Answers

I finally figured out what my problem was. It all came down to a single line I'd forgot to add. In my FragmentActivity subclass I'd overrode onSaveInstanceState, but I never called super.onSaveInstanceState. Apparently, unlike other methods whose parents I'd forgotten to call, onSaveInstanceState won't throw a runtime error when I forget to call the parent classes version of it, instead setRetainInstance just stops working. I hope this saves someone the headache I went through trying to solve this.

like image 101
rofer Avatar answered Sep 19 '22 04:09

rofer


It seems, when you set setRetainInstance = true while both onSaveInstanceState() and onActivityCreated() are called, then Bundle will not be returned.

However, as the as the ListFragment is being retained, you can simply store its state into a field, and handle it inside onActivityCreated().

Bear in mind, the Activity will still be destroyed and recreated.

like image 31
dezull Avatar answered Sep 21 '22 04:09

dezull