For my Android application, I get several unmarshalling errors although I think I\'ve done everything that is needed to properly save and load objects via Parcelable
Before reading from bundle, set ClassLoader:
bundle.setClassLoader(getClass().getClassLoader());
This saved my time!
By the look of it, the createFromParcel
and newArray
should be overridden like this:
public static final Parcelable.Creator<MyObject> CREATOR = new Parcelable.Creator<MyObject>() {
@Override
public MyObject createFromParcel(Parcel in) {
MyObject myObj = new MyObject();
myObj.intArray = in.readIntArray(...);
myObj.intValue = in.readInt(...);
// ....
// IN THE SAME ORDER THAT IS WRITTEN OUT AS PER writeToParcel!
//
return myObj;
}
@Override
public MyObject[] newArray(int size) {
return new MyObject[size];
}
};
Edit:
I forgot to mention that for the above to work, there should have been an empty constructor!
public MyObject(){}
Android has two different classloaders: the framework classloader (which knows how to load Android classes) and the APK classloader (which knows how to load your code). The APK classloader has the framework classloader set as its parent, meaning it can also load Android classes.
Error #2 is likely caused by the Bundle using the framework classloader so it doesn't know of your classes. I think this can happen when Android needs to persist your Bundle and later restore it (for example when running out of memory in the background). You can fix this by setting the APK classloader on the bundle:
savedInstanceState.setClassLoader(getClass().getClassLoader());
Error #1 and #3 are more mysterious, are you perhaps writing null values in writeToParcel()
? Android doesn't like that very much I'm afraid.