In onSaveInstanceState()
:
// departures is instance of Departures which extends ArrayList
bundle.putSerializable("departures", departures);
In onRestoreInstanceState
:
departures = (Departures) state.getSerializable("departures");
When I rotate the screen, the Activity is restarted and it's state is restored. It works ok. In case I leave the Activity, after some time Android removes it from memory and saves its state. When I return to it, it crashes in onRestoreInstanceState
:
java.lang.ClassCastException: java.util.ArrayList cannot be cast to cz.fhejl.pubtran.Departures
The getSerializable
now returned ArrayList
, not Departures
.
Edit: here's how Departures.java looks: http://pastebin.com/qc3QfrK7
The problem you see is caused by the way Android flattens the objects. Internally it will call Parcel#writeValue(Object)
which has a long chain of if / else and the if (o instanceof List)
comes before instanceof Serializable
. Since Departures
is a List
it will put it as a list instead and when unparcelling the data it does not know that it was a special kind of list.
You need to use something that does not extend a List
to get around that problem.
I know I am a bit late on this one but I came across a similar problem with an array of serializables.
I made it work by wrapping the array within a private class of my own.
private class ArrayHolder implements Serializable{
public Serializable[] _myArray;
public ArrayHolder(Serializable myArray){
_myArray = myArray;
}
}
Then to save all I did was
bundle.putSerializable("name",new ArrayHolder(arrayToBeSaved));
When deserializing:
ArrayHolder arrayHolder = (ArrayHolder) bundle.getSerializable("name");
arrayRecovered = arrayHolder._myArray;
I have no idea WHY it works but it does.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.