Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fragment within Tab Activity losing all data when rotating?

I am using the Sherlock ActionBar library and I have a SherlockFragmentActivity implementing ActionBar.TabListener (for my tabs) and I have 3 tabs...each being a SherlockFragment. When I rotate, the entire Activity is recreated and I lose all variables declared in my onCreate within the Fragment. How would I go about fixing this?

I figured I should be using fragments as tabs instead of activities...is this wrong?

EDIT: I should mention that my current workaround is to have static Lists in the Tab Activity and have the fragment push stuff to those lists on onPause (and get stuff back from them on onResume). I REALLY don't like doing this and I know there has to be a better way.

Also, regarding if(savedInstanceState==null), I've tried that and it doesn't seem to work. I think it's because the Activity that holds my Fragments is being recreated and the tabs need to be recreated.

like image 960
snotyak Avatar asked Aug 05 '12 10:08

snotyak


1 Answers

There's a method called setRetainInstance() in the Fragment class, that you need to set to true. That'll save the instance of your fragments, and you can then check for any saved instances in onCreate().

More info available here: http://developer.android.com/reference/android/app/Fragment.html

like image 115
Michell Bak Avatar answered Sep 30 '22 18:09

Michell Bak