android runtime_error ai_generated true

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

其他格式: JSON · Markdown 中文 · English
92%修复率
89%置信度
1证据数
2023-12-01首次发现

版本兼容性

版本状态引入弃用备注
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.

generic

官方文档

https://developer.android.com/guide/components/activities/activity-lifecycle#saving-state

解决方案

  1. Add a null check before accessing the bundle: `if (savedInstanceState != null) { val data = savedInstanceState.getSerializable("key") }`
  2. 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") } }`

无效尝试

常见但无效的做法:

  1. 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.

  2. 90% 失败

    Calling super.onCreate() is already standard practice; the NPE occurs because `savedInstanceState` itself is null, not because it's accessed before super call.