如何在共享偏好中保存一些值并在下一个活动中获取

时间:2013-02-26 06:37:14

标签: android sharedpreferences

我正在创建一个测验应用程序,我会问一些问题并以单选按钮的形式提供选项,现在我想在{{1}中存储答案的值(加上正确的答案和减去错误的答案)并显示其他活动的结果。我搜索过并找到了answer here

我用过但仍然无法得到我想要的结果 我的代码看起来像:

主要活动,可以在SharedPreferences中保存一些价值:

SharedPreferences

这是尝试从public class MainActivity extends Activity { private SharedPreferences saveScore; private SharedPreferences.Editor editor; RadioGroup group; RadioButton radioButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); group = (RadioGroup) findViewById(R.id.radioGroup1); radioButton = (RadioButton) group.findViewById(group.getCheckedRadioButtonId()); saveScore = getPreferences(MODE_PRIVATE); } public void gotoNextAndSaveScore(View view) { if(group.getCheckedRadioButtonId() != R.id.radio3){ editor = saveScore.edit(); editor.putInt("score", -1); editor.commit(); }else{ editor = saveScore.edit(); editor.putInt("score", 1); editor.commit(); } Intent intent = new Intent (MainActivity.this, NextActivity.class); startActivity(intent); }} 获取值的下一个活动:

SharedPreferences

有人知道怎么做吗?

4 个答案:

答案 0 :(得分:3)

您应该更改

 saveScore = getPreferences(MODE_PRIVATE);      

saveScore =  getSharedPreferences("score",Context.MODE_PRIVATE);

答案 1 :(得分:1)

试试这个,

public class DataStorage {

private static String KEY;
public static SharedPreferences savedSession;

public void saveID(Context context, String msessionid) {
    // TODO Auto-generated method stub

    Editor editor = context
            .getSharedPreferences(KEY, Activity.MODE_PRIVATE).edit();
    editor.putString("SESSION_UID", msessionid);
    editor.commit();
}

public String getID(Context context) {

    savedSession = context.getSharedPreferences(KEY, Activity.MODE_PRIVATE);
    return savedSession.getString("SESSION_UID", "");
}
}

修改

 DataStorage mdata = new DataStorage();

public void gotoNextAndSaveScore(View view) {
if(group.getCheckedRadioButtonId() != R.id.radio3){

   mdata.saveId(Mainactivity.this,1);
}else{
   mdata.saveId(Mainactivity.this,-1);
}   

然后从NextActivity获取价值。

DataStorage mdata = new DataStorage();
mdata.getId(NextActivity.this);

答案 2 :(得分:1)

nextActivity期间导航到onPause()时存储值,如下所示:

    @Override
    protected void onPause() 
    {
      super.onPause(); 
      // Store values between instances here
      SharedPreferences preferences = getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE);
      SharedPreferences.Editor editor = preferences.edit();
      editor.putString("YourStringKeyValue", "StringValue"); // value to store
      // Commit to storage
      editor.commit();
    }

并在next Activity的{​​{1}}中获取包含该密钥的数据,如下所示:

onCreate

答案 3 :(得分:0)

您使用了错误的首选项文件,Activity上的getPreference函数会返回该Activity的私有文件。您需要使用命名文件version- getSharedPreferences(name,mode)