来自不同活动的SharedPreferences

我从以下方式从活动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(); } 

在活动BI想要加载SharedPreferences。 以下是一个NullPointerException:

 private void LoadPreferences(){ SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); data = sharedPreferences.getString("name", "08:00") ; } 

如果我试着跟随,我得到这个编译错误:“范围内没有typesA的封闭实例”

 private void LoadPreferences(){ SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(A.this); data = sharedPreferences.getString("name", "08:00") ; } 

我怎样才能访问数据?

Solutions Collecting From Web of "来自不同活动的SharedPreferences"

在两个Activities中使用getApplicationContext()代替this

在活动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); } 

并在活动B中获得价值为:

  private void LoadPreferences(){ SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); String data = sharedPreferences.getString("name", "08:00") ; Toast.makeText(this,data, Toast.LENGTH_LONG).show(); } 

因为如doc所说:

getDefaultSharedPreferences(上下文上下文) :

获取一个SharedPreferences实例,该实例指向给定上下文中的首选项框架使用的默认文件。

要在共享首选项中存储值:

 SharedPreferences preferences==PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor editor=preferences.edit(); editor.putString("Name","Harneet"); editor.commit(); 

从共享首选项中检索值:

 SharedPreferences preferences==PreferenceManager.getDefaultSharedPreferences(this); String name=preferences.getString("Name",""); if(!name.equalsIgnoreCase("")) { name=name+" Sethi"; /* Edit the value here*/ } 

编辑来自sharedpreference的数据

 SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit(); editor.putString("text", mSaved.getText().toString()); editor.putInt("selection-start", mSaved.getSelectionStart()); editor.putInt("selection-end", mSaved.getSelectionEnd()); editor.commit(); 

从共享首选项中检索数据

 SharedPreferences prefs = getPreferences(MODE_PRIVATE); String restoredText = prefs.getString("text", null); if (restoredText != null) { //mSaved.setText(restoredText, TextView.BufferType.EDITABLE); int selectionStart = prefs.getInt("selection-start", -1); int selectionEnd = prefs.getInt("selection-end", -1); /*if (selectionStart != -1 && selectionEnd != -1) { mSaved.setSelection(selectionStart, selectionEnd); }*/ }