首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android SharedPreferences 空指針異常排查指南

     編輯:程式設計綜合問答

異常堆棧分析

java.lang.NullPointerException: Attempt to read from field 
'android.content.SharedPreferences org.droidplanner.android.utils.prefs.DroidPlannerPrefs.prefs' 
on a null object reference

核心原因

`DroidPlannerPrefs.prefs` 字段為 `null`,嘗試訪問其方法導致 NPE。典型場景:

  • `SharedPreferences` 未正確初始化
  • 單例模式實現有缺陷
  • Context 為 null 或錯誤類型
  • 多進程環境下共享偏好設置異常

排查步驟

1. 斷點調試(最直接)

  • 在 `FlightActivity.onResume()` 設置斷點
  • 檢查 `DroidPlannerPrefs` 實例化過程
  • 觀察 `prefs` 字段賦值時機

2. 代碼審查關鍵點

// 典型錯誤模式
public class DroidPlannerPrefs {
    public SharedPreferences prefs;  // 未初始化
    
    public static DroidPlannerPrefs getInstance() {
        return new DroidPlannerPrefs();  // 每次新建,prefs 為 null
    }
}

// 正確單例模式
public class DroidPlannerPrefs {
    private static DroidPlannerPrefs instance;
    private final SharedPreferences prefs;
    
    private DroidPlannerPrefs(Context context) {
        this.prefs = context.getSharedPreferences("name", Context.MODE_PRIVATE);
    }
    
    public static synchronized DroidPlannerPrefs getInstance(Context context) {
        if (instance == null) {
            instance = new DroidPlannerPrefs(context.getApplicationContext());
        }
        return instance;
    }
}

3. 常見坑點

問題解決方案
在 Application 未創建前調用確保在 Activity/Service 中調用,或使用 Application Context
使用 Activity Context 導致洩漏傳入 `context.getApplicationContext()`
多進程數據不同步使用 `MODE_MULTI_PROCESS` (API 23 棄用) 或 ContentProvider 方案
ProGuard 混淆導致字段丟失添加 `-keep` 規則保留模型類

快速修復清單

  1. 檢查 `DroidPlannerPrefs` 構造函數是否正確獲取 `SharedPreferences`
  2. 確認單例獲取上下文方式正確
  3. 在 `FlightActivity` 中確保調用前已初始化
  4. 添加空值守衛:`if (prefs != null) { ... }`
  5. 升級至 DataStore(Jetpack 現代替代方案)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved