android - 当不保持启用 Activity 时,矢量恢复为 ArrayList onRestoreInstanceState

标签 android

简单的测试用例 100% 可重现。 尝试在开发者选项中启用“不保留 Activity ”。

1 - 成为 Activity “Vector”(或 Vector 的任何子类)的成员。

2 - onSaveInstanceState 使用“putSerializable”将您的矢量成员 bundle 在一起

3 - 转到其他 Activity (例如按下按钮并打开新 Activity )

4 - 在新 Activity 中,按返回按钮完成它。

5 - 确保从您在 onCreate 中收到的 savedInstanceState 包中获取您的向量。

6 - 崩溃!

java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.util.Vector

是我做错了什么,还是平台出了问题?

最佳答案

所有的List在bundle传递时都会被重建成ArrayList。

当在activity之间传输数据时,bundle中实现Serializable的所有数据都会被写入字节流,并在新的activity中重新创建。

当您调用 bundle.getSerializable() 时,它将使用 readValue()android.os.Parcel获取值。在Parcel.java的源代码中, 它使用 readArrayList()当对象是List的子类时创建List的方法,它不会关心之前 Activity 中是Vector还是其他。

public final Object readValue(ClassLoader loader) {
    int type = readInt();

    switch (type) {
        case VAL_STRING:
            return readString();
            ...
        case VAL_LIST:
            return readArrayList(loader);
            ....
    }
}

关于android - 当不保持启用 Activity 时,矢量恢复为 ArrayList onRestoreInstanceState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32757450/

相关文章:

html - android HTML 模板作为资源

android - 使用合并适配器;在 ListActivity onListItemClicked 方法中寻找确定列表项数据类型的方法

java - 如何在不使用图像加载库的情况下修复 OutOfMemoryError

安卓.view.InflateException : Binary XML file line #1: error inflating class fragment/from an emulator

php - 通过 Android 应用程序运行 php 脚本

android - Android 上的 ifconfig 和 route 命令

android - Xamarin.Forms 如何显示互联网连接已更改?

android - sync_extras_upload 有什么用?

android - Android 中带改造的简单类型 Joda 日期时间

android - 如何在自定义 View 中重复一个模式到边界?