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。典型場景:
// 典型錯誤模式
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;
}
}
| 問題 | 解決方案 |
|---|---|
| 在 Application 未創建前調用 | 確保在 Activity/Service 中調用,或使用 Application Context |
| 使用 Activity Context 導致洩漏 | 傳入 `context.getApplicationContext()` |
| 多進程數據不同步 | 使用 `MODE_MULTI_PROCESS` (API 23 棄用) 或 ContentProvider 方案 |
| ProGuard 混淆導致字段丟失 | 添加 `-keep` 規則保留模型類 |