简体   繁体   中英

Android Parcelable casting error

So I'm about to crazy with this issue.

The main point is as following:
I have an Object that implements Parcelable . This object is passed around between Activities easily and without issues.
But if I attempt to read it from a Bundle in onRestoreInstanceState , after storing it with onSaveInstanceState , I get an exception about casting to invalid class. Below is the code for storing and reading, plus the Exception thrown.

onSaveInstanceState

Log.d(TAG, "Address is null:" + (userAddress == null));
if( userAddress != null )
{
    Log.d(TAG, "Address class:" + userAddress.getClass());
}

saveInto.putParcelable("UserAddress", userAddress); <-- Storing here


onRestoreInstanceState

Log.d(TAG, "Contains: " + retrieveFrom.keySet().contains("UserAddress"));

userAddress = retrieveFrom.getParcelable("UserAddress"); <-- Reading here

Log.e(TAG, "Loaded-Address was null:" + (userAddress == null));


Exception

W/Bundle﹕ Key UserAddress expected Parcelable but value was a java.lang.String.  The default value <null> was returned.
W/Bundle﹕ Attempt to cast generated internal exception:
java.lang.ClassCastException: java.lang.String cannot be cast to android.os.Parcelable
    at android.os.Bundle.getParcelable(Bundle.java:810)
    ...


The log shows that right before storing, the object is not null and the correct class. But after retrieving, it's null.
I have found a Android Bug that mentions something like this, but not exactly:
https://code.google.com/p/android/issues/detail?id=38303

The Object does not contain anything other than Primitive data like Strings and Longs.
Any ideas or suggestions are much appreciated.

Key UserAddress expected Parcelable but value was a java.lang.String .

That indicates that the Bundle contains a String

The reason is that somewhere you call

saveInto.putString("UserAddress", "something");

and that overrides the other value that you try to save into the Bundle.

I would recommend using more specific keys, and declaring them in a separated config file, so you can see in one glance who uses them.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM