Android Fragment: How To Save An Instance
Solution 1:
Depends what you want to do with the data and fragment:
- Do you want to rebuild the fragment with previous data?
- Do you want to keep the instance in memory and reopen it?
For case 1, I would suggest you to use more permanent data storage and save the data in onStop of the fragment. Then you can check in onCreateView to see if data exist and load the data back if exist. You can easily use sharePref to do that, and it takes 3 lines of code to read and write. I would suggest this if the data is only location and some strings. You can further extend this by using timestamp on the store data, if it's too long, you can ignore the previous data and load again which is useful for location data.
@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
...
SharedPreferencesprefs= PreferenceManager.getDefaultSharedPreferences(mContext);
StringpreviousData= prefs.getString("locationData"), null);
if(previousData != null)
{
//Do something with data.
}
else {
try {
// Loading map and retrives locations from server
initilizeMap();
} catch (Exception e) {
Log.e("ERROR", "ERROR IN CODE: " + e.toString());
e.printStackTrace();
}
}
}
@OverridepublicvoidonStop()
{
Log.i(TAG, "onStop");
super.onStop();
SharedPreferencesprefs= PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editoreditor= prefs.edit();
editor.putString("locationData"), [your data]);
}
Using onSaveInstanceState to save data is for configuration change, not for a fragment being destroyed (using transaction replace). http://developer.android.com/reference/android/app/Fragment.html#setRetainInstance(boolean)
For case 2, you can just use show and hide on your fragment so that it doesn't get destroyed, but then you have to modify your layout to have more than 1 container. http://developer.android.com/reference/android/app/FragmentTransaction.html I don't recommend doing it this way unless your activity is designed to have multi fragments showing at the same time.
Post a Comment for "Android Fragment: How To Save An Instance"