Bam
Bam

Reputation: 530

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.

Upvotes: 1

Views: 10360

Answers (1)

njzk2
njzk2

Reputation: 39397

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.

Upvotes: 5

Related Questions