在 Activity A 寫入、Activity B 讀取 SharedPreferences 時,若直接用 this(Activity Context)或 A.this,會因 Context 不同導致資料隔離或 NullPointerException。
// 寫入(任意位置)
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
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)避免衝突。