Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird ClassCastException when deserializing in onRestoreInstanceState

Tags:

android

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

like image 996
fhucho Avatar asked Sep 08 '12 20:09

fhucho


2 Answers

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.

like image 57
zapl Avatar answered Dec 14 '22 23:12

zapl


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.

like image 40
theblitz Avatar answered Dec 15 '22 00:12

theblitz