【发布时间】:2021-12-04 14:59:17
【问题描述】:
所以我要为这个问题发疯了。
要点如下:
我有一个实现Parcelable 的Object。此对象在Activities 之间轻松传递,没有问题。
但是,如果我尝试从onRestoreInstanceState 中的Bundle 读取它,在使用onSaveInstanceState 存储它之后,我会收到关于强制转换为无效类的异常。下面是存储和读取的代码,加上抛出的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)
...
日志显示,在存储之前,对象不为空且类正确。但检索后为空。
我发现了一个 Android 错误,其中提到了类似的内容,但不完全是:
https://code.google.com/p/android/issues/detail?id=38303
该对象不包含除原始数据(如字符串和长整数)之外的任何内容。
非常感谢任何想法或建议。
【问题讨论】:
-
一定有你打电话给
putString("UserAddress", "something");的地方 -
您可能应该包含显示您的 Parcelable 实现的对象的代码
-
userAddress是字符串还是你的对象? -
耶稣现在带我去!! @njzk2:我在
Activities超类onSaveInstanceState的某个地方打电话给putString("UserAddress", some string);。给我一杯啤酒!! (如果您发布答案@njzk2,我可以接受答案。)
标签: java android parcelable