Friday, August 2, 2013

Saving and Retrieving android fragment state OnSaveInstanceState



What methods of Fragment are get called when configuration changes ?


One difference between a fragment and an activity is that there is no onRestoreInstanceState( ) method to retrieve and restore the state in a fragment.  Instead, the fragment’s on onCreate( ), onCreateView( ) and onActivityCreated( ) lifecycle methods all get passed the Bundle object.  You can use these methods and the passed in Bundle containing the fragment’s saved state to restore any state you need.  Keep in mind, the Bundle passed to these methods will be null unless the system is recreating the fragment (i.e. this is not the first time the methods are called on the fragment).  So when trying to restore state, put a null check in place to before accessing the Bundle.

Just like an activity, a fragment will automatically save the data of any fragment View component in the Bundle by the View component’s id. And just like in the activity, if you do implement the onSaveInstanceState( ) method make sure you add calls to the super.onSaveInstanceState( ) methods so as to retain this automatic save of View data feature.





image




When the device is rotated (portrait to landscape or vice versa), the device changes its runtime configuration – causing a destroy and recreation of the activities and fragments.  Other configuration changes include the change of a language, addition or removal of an input device (such as a keyboard), or when a device changes dock status (when a device is plugged into/unplugged from a car or desk dock).

 How to retain the fragment instance during configuration changes? when setRetainInstance(true) is called, what would be the fragment lifecycle methods?


On the Fragment class is a pair of get/set methods called setRetainInstance( ) and getRetainInstance( ).  The setter takes a boolean and the getter, obviously, returns a boolean.  The boolean is an indication of whether a fragment instance should be retained across any associated activity’s re-creation during such actions as a configuration change.  In other words, a fragment instance does not have to be completely destroyed and recreated when an activity is destroyed and recreated.  If a fragment is told to retain its instance with a call to setRetainInstance(true), then the fragment lifecycle is altered such that the fragment’s onDestroy( ) and onCreate( ) methods will not be called and the existing instance is associated to the new activity instance.

image

onCreate and onDestroy would not be called .we should save anything in the onsavedinstance(Bundle bundle) bundle  and retrieved in onActivityCreated() with null check.


On the orientation change of a device, for example, the existing instance of a fragment is provided to the new instance of the associated activity when it gets recreated.