Android Parcelable 投射错误

Android Parcelable casting error

所以我快要被这个问题搞疯了。

要点如下:
我有一个实现 ParcelableObject。此对象在 Activities 之间轻松无误地传递。
但是,如果我尝试从 onRestoreInstanceState 中的 Bundle 中读取它,在将其存储为 onSaveInstanceState 后,我会得到一个关于强制转换为无效 class 的异常。下面是存储和读取的代码,加上抛出的Exception

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)
    ...


日志显示,就在存储之前,对象不为空且正确 class。但是取回后是null
我发现了一个 Android Bug,它提到了这样的事情,但不完全是:
https://code.google.com/p/android/issues/detail?id=38303

该对象不包含除原始数据(如字符串和长整型)以外的任何内容。
非常感谢任何想法或建议。

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

表示Bundle包含一个String

原因是你在某个地方打电话

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

这会覆盖您尝试保存到捆绑包中的其他值。

我建议使用更具体的密钥,并在单独的配置文件中声明它们,这样您一眼就能看出谁在使用它们。