Reputation: 670
In my application I have activity A.Upon clicking a button on this Activity, app launches Activity B.Inside Activity B's onCreate() I add a fragment.Everytime a fragment is created it loads a list from External Server using AsyncTask.
How can I persist this list on configuration changes?I have looked for many solutions but many suggest using 'android:configchanges' in manifest which I am totally against using.Many suggest and I have read about it also - to use setRetainInstance(true) in Fragment that would retain the fragment.
I have tried to implement it but I failed.Many tutorials after orientation changes check for the Fragment using findFragmentByTag but in my case it always returns null.Can anybody please post proper tutorial or proper answer on how to use RetainFragments?
Also I am calling AsyncTask to load list in onActivityCreated method in Fragment.According to android documentation when using setRetainInstance(true),onCreate(Bundle) will not be called since the fragment is not being re-created. onAttach(Activity) and onActivityCreated(Bundle) will still be called.
So should I call AsyncTask in onCreate Method?
Upvotes: 1
Views: 1929
Reputation: 270
Check this. This tutorial is for retaining MediaPlayer instance across orientation changes. its very straight forward. it used setRetainInstance(true) of fragment to retain MediaPlayer over orientation change.
This portion explains the callback of fragment fired during orientation chage
onAttach - always
onCreate - not on configuration change
onStart - always
onResume - always
onPause - always
onStop - always
onDestroy - not on configuration change
onDetach - always
So just Create a reference to your server response in this fragment and make call to server in onCreate.
You can use activity's isChangingConfigurations() method to know whether fragment's life cycle is called because of orientation changes or fragment is being destroyed if you want to release some resources.
In activity use FragmentManager to check whether there is an instance of the fragment already exists, if not create new one and add it.
Upvotes: 1
Reputation: 36069
I'm not sure if you remember this:
Caution: Your activity will be destroyed and recreated each time the user rotates the screen. When the screen changes orientation, the system destroys and recreates the foreground activity because the screen configuration has changed and your activity might need to load alternative resources (such as the layout).
I higly recommend you this post:
Handling Configuration Changes with Fragments
http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html
Note: In order for the Android system to restore the state of the views in your activity, each view must have a unique ID, supplied by the android:id attribute.
Source: http://developer.android.com/training/basics/activity-lifecycle/recreating.html
Upvotes: 2