android runtime_error ai_generated true

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

Also available as: JSON · Markdown · 中文
92%Fix Rate
89%Confidence
1Evidence
2023-12-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
Android 11 (API 30) active
Android 14 (API 34) active
AndroidX Activity 1.8.0 active

Root Cause

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

中文

活动被重新创建(例如,旋转或进程终止后),`savedInstanceState` 为 null,但代码尝试从 bundle 中检索可序列化对象而没有进行空检查。

Official Documentation

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 70% fail

    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% fail

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