来自不同活动的SharedPreferences

时间:2012-07-03 18:01:30

标签: android

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

在活动B中,我想加载SharedPreferences。以下是NullPointerException:

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

如果我尝试跟随,我会收到此编译错误:“在范围内无法访问类型A的封闭实例”

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

如何访问数据?

2 个答案:

答案 0 :(得分:42)

在两个活动中使用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();
   }

因为正如医生所说:

getDefaultSharedPreferences(Context context)

  

获取指向默认文件的SharedPreferences实例   在给定的上下文中由首选框架使用。

答案 1 :(得分:2)

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

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*/
  }

编辑来自共享偏好的数据

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);
  }*/
}