You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

屏幕旋转时调用savedInstanceState.getParcelableArrayList遇空指针异常

解决旋转屏幕时Parcelable ArrayList恢复失败的NullPointerException问题

你遇到的这个崩溃问题根源非常明确——你重写了错误的onSaveInstanceState重载方法,导致数据根本没有被保存到Bundle中,恢复时自然拿到null,后续调用ArrayList.size()就触发了空指针异常。

问题具体出在哪里

看你的Activity代码,你重写的是这个方法:

@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
    super.onSaveInstanceState(outState, outPersistentState);
    outState.putParcelableArrayList("key", arrayListPatientInfo);
}

这个带PersistableBundle参数的重载方法,只有在你给Activity在Manifest里配置了android:persistableMode="persistAcrossReboots"时才会被系统调用。而默认情况下,屏幕旋转时系统会调用仅接收Bundle参数的onSaveInstanceState方法,你完全没覆盖这个默认方法,所以旋转时数据根本没被保存,savedInstanceState里找不到"key"对应的ArrayList,getParcelableArrayList自然返回null。

修复方案

把onSaveInstanceState改成正确的重载版本即可:

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putParcelableArrayList("key", arrayListPatientInfo);
}

注意这个方法的签名:是protected修饰符,只接收一个Bundle参数,不需要PersistableBundle。

额外验证

你的RecyclerViewItemPatientInfo类的Parcelable实现是完全正确的——构造函数、CREATOR、writeToParcel方法的读写逻辑完全对应,所有字符串都正确处理,describeContents返回0也符合普通Parcelable的要求,这个类本身没有问题,不需要修改。

修改后再旋转屏幕,arrayListPatientInfo就能正确从savedInstanceState中恢复,空指针异常也就不会再出现了。

内容的提问来源于stack exchange,提问作者hưng nguyễn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:26:27