gpt4 book ai didi

android - 如何在 sharedpreferences 中保存一些值并在下一个 Activity 中获取它

转载 作者:行者123 更新时间:2023-11-29 15:23:51 24 4
gpt4 key购买 nike

我正在创建一个测验应用程序,我提出了一些问题并以单选按钮的形式给出了选项,现在我想在 SharedPreferences 中存储答案的值(正确答案加上,错误答案减去) 并在其他 Activity 中显示该结果。我搜索并找到了这个 answer here

我使用了它,但仍然无法获得我想要的结果我的代码看起来像:

SharedPreferences 中保存一些值的主 Activity :

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 获取值的 Next Activity:

public class NextActivity extends Activity{

private SharedPreferences preferences;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);

preferences = this.getSharedPreferences("score", MODE_WORLD_WRITEABLE);

int value = preferences.getInt("score", 0);
String score = "Your Score is : " + value;
UIHelper.displayScore(this, R.id.tvScore, score );

}}

有人知道怎么做吗?

最佳答案

你应该换行

 saveScore = getPreferences(MODE_PRIVATE);      

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

关于android - 如何在 sharedpreferences 中保存一些值并在下一个 Activity 中获取它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15082883/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com