【问题标题】:Android Parcelable casting errorAndroid Parcelable 转换错误
【发布时间】:2021-12-04 14:59:17
【问题描述】:

所以我要为这个问题发疯了。

要点如下:
我有一个实现ParcelableObject。此对象在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


【解决方案1】:

UserAddress 预期为 Parcelable,但值为 java.lang.String

这表示 Bundle 包含 String

原因是你打电话的地方

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多