I have some state that I want to save accross the lifecycle of a fragment. It works fine when the screen rotates for example, but when the process has been killed and restored from disk (I think that's how it works), I get a ClassCastException.
Here's some code:
Initialization:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
playlistsMap = new LinkedHashMap<Section, List<Playlist>>();
} else {
playlistsMap = (LinkedHashMap<Section, List<Playlist>>) savedInstanceState.getSerializable(PLAYLISTS_MAP_KEY);
}
setHasOptionsMenu(true);
}
Saving the data :
@Override
public void onSaveInstanceState(Bundle outState) {
if (isEverySectionsLoaded()) {
outState.putSerializable(PLAYLISTS_MAP_KEY, playlistsMap);
} else {
outState.putSerializable(PLAYLISTS_MAP_KEY, new LinkedHashMap<Section, List<Playlist>>());
}
// ...
}
The exception I get from the cast in onCreate
:
04-10 01:06:43.430 E/AndroidRuntime(28549): FATAL EXCEPTION: main
04-10 01:06:43.430 E/AndroidRuntime(28549): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mydomain.android/com.mydomain.android.ui.MainActivity}:
java.lang.ClassCastException: java.util.HashMap cannot be cast to java.util.LinkedHashMap
I know it's better to use parcelables on Android, but I still don't understand how that could ever happen.
Any ideas?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…