java.lang.RuntimeException:无法启动活动 ComponentInfo{com.example/com.example.MainActivity}:java.lang.NullPointerException:尝试对 null 对象引用调用虚拟方法 'java.lang.Object android.os.Bundle.getSerializable(java.lang.String)'
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example/com.example.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.os.Bundle.getSerializable(java.lang.String)' on a null object reference
ID: android/activity-recreated-savedinstancestate-null
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Android 11 (API 30) | active | — | — | — |
| Android 14 (API 34) | active | — | — | — |
| AndroidX Activity 1.8.0 | active | — | — | — |
根因分析
活动被重新创建(例如,旋转或进程终止后),`savedInstanceState` 为 null,但代码尝试从 bundle 中检索可序列化对象而没有进行空检查。
English
Activity is recreated (e.g., after rotation or process death) and `savedInstanceState` is null, but the code attempts to retrieve a serializable object from the bundle without null check.
官方文档
https://developer.android.com/guide/components/activities/activity-lifecycle#saving-state解决方案
-
Add a null check before accessing the bundle: `if (savedInstanceState != null) { val data = savedInstanceState.getSerializable("key") }` -
Use `onSaveInstanceState` to persist data and `onRestoreInstanceState` to restore it safely with null checks: `override fun onRestoreInstanceState(savedInstanceState: Bundle) { super.onRestoreInstanceState(savedInstanceState); if (savedInstanceState.containsKey("key")) { val data = savedInstanceState.getSerializable("key") } }`
无效尝试
常见但无效的做法:
-
70% 失败
This only prevents recreation due to orientation changes, not process death or other configuration changes (e.g., locale). The NPE still occurs in other scenarios.
-
90% 失败
Calling super.onCreate() is already standard practice; the NPE occurs because `savedInstanceState` itself is null, not because it's accessed before super call.