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 theif (o instanceof List)comes beforeinstanceof Serializable. SinceDeparturesis aListit 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
Listto get around that problem.