24

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

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

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

如何访问数据?

4

2 回答 2

48

在两个活动中使用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(上下文上下文)

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

于 2012-07-03T18:21:16.130 回答
3

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

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);
  }*/
}
于 2012-07-03T18:15:35.557 回答