【发布时间】:2020-08-02 00:57:38
【问题描述】:
我在 SharedPreferences 中保存布尔对象时遇到问题。该对象(ArrayList“问题”的一部分)包含一个布尔值“recentAnswer”。 如果我更改布尔值并想在另一个活动中使用它,则该值仍然是旧的。
这是我在活动 1 中的 saveData 方法:
private void saveData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(questions);
editor.putString("task list", json);
editor.apply();
}
我在这里使用它来保存更改后的布尔值(活动 1):
private void checkAnswer(Button answerButton){
if (answerButton.getText().equals(questions.get(currentQuestion).getAnswer1())){
questions.get(currentQuestion).recentAnswer = true;
}
else{
questions.get(currentQuestion).recentAnswer = false;
}
Toast.makeText(this, Boolean.toString(questions.get(currentQuestion).recentAnswer), Toast.LENGTH_SHORT).show();
saveData();
}
首先,我在 Activity 2 中加载 ArrayList:
private void loadData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("task list", null);
Type type = new TypeToken<ArrayList<Question>>(){}.getType();
questions = gson.fromJson(json, type);
if(questions == null){
questions = new ArrayList<>();
}
}
然后我想获取“recentAnswer”值(活动 2):
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_statistics);
loadData();
for (Question element : questions){
int recentWrong;
if (!element.recentAnswer){
recentWrong++;
}
}
Toast.makeText(this, Integer.toString(recentWrong), Toast.LENGTH_SHORT).show();
}
不管我如何更改活动 1 中的值,在活动 2 中“recentWrong”始终 = 0,即使我正在访问问题。
【问题讨论】:
标签: android json arraylist boolean sharedpreferences