我用下面的代碼從 activity A 中加載 SharedPreferences:
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
在 activity B 中我想加載 SharedPreferences。下面是一個異常 NullPointerException:
private void LoadPreferences(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
data = sharedPreferences.getString("name", "08:00") ;
}
我用下面的代碼,得到這個編譯錯誤:"No enclosing instance of the type A is accessible in scope"
private void LoadPreferences(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(A.this);
data = sharedPreferences.getString("name", "08:00") ;
}
如何訪問數據?謝謝!
在兩個 Activities 中把 this 替換為 getApplicationContext()
在Activity A 的 SharedPreferences 是下面的方式:
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
Intent sd=new Intent(this,Secongtess.class);
startActivity(sd);
}
Activity B 中按下面的方式獲取值:
private void LoadPreferences(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String data = sharedPreferences.getString("name", "08:00") ;
Toast.makeText(this,data, Toast.LENGTH_LONG).show();
}