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

Android SharedPreferences 跨 Activity 正確讀寫:使用 Application Context

     編輯:程式設計綜合問答

常見錯誤與原因

在 Activity A 寫入、Activity B 讀取 SharedPreferences 時,若直接用 this(Activity Context)或 A.this,會因 Context 不同導致資料隔離或 NullPointerException。

正確做法:統一使用 Application Context

// 寫入(任意位置)
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
sp.edit().putString("key", "value").apply();

// 讀取(任意位置)
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String val = sp.getString("key", "default");

getApplicationContext() 回傳全程單一的 Application 實例,確保所有組件存取同一組預設 SharedPreferences 檔案(/data/data/pkg/shared_prefs/pkg_preferences.xml)。

完整範例:Activity A 寫入 → 啟動 Activity B 讀取

// Activity A
private void saveAndJump() {
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    sp.edit().putString("name", "08:00").apply();
    startActivity(new Intent(this, ActivityB.class));
}

// Activity B
private void loadAndShow() {
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    String data = sp.getString("name", "08:00");
    Toast.makeText(this, data, Toast.LENGTH_LONG).show();
}

進階建議

  • 使用 apply() 非同步寫入,避免阻塞主執行緒;需立即持久化才用 commit()。
  • 若需多進程共享,建議改用 DataStore(Jetpack)或自訂 ContentProvider。
  • 鍵值命名建議加前綴(如 pref_user_name)避免衝突。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved