屏幕旋转时调用savedInstanceState.getParcelableArrayList遇空指针异常
你遇到的这个崩溃问题根源非常明确——你重写了错误的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

