我设法将得分正确保存到SharedPreferences以及保存到高分。但是,当检查以前的分数是否优于保存的高分时,无论如何都会保存,并且我不知道为什么。
// save score and time if current score is > than current highscore and time is > than current hightime
if (score > scorePreferences.getInt("highscore", 0) && time > timePreferences.getInt("hightime", 0)) {
highscorePreferences = getContext().getSharedPreferences("highscore", 0);
SharedPreferences.Editor editorHighscore = highscorePreferences.edit();
editorHighscore.putInt("highscore", score);
editorHighscore.commit();
timePreferences = getContext().getSharedPreferences("hightime", 0);
SharedPreferences.Editor editorHightime = timePreferences.edit();
editorHightime.putInt("hightime", time);
editorHightime.commit();
}
然后使用此代码读取游戏活动和高分数活动:
// load score from last session
private void load() {
// get score and set text field
scorePreferences = getSharedPreferences("score", 0);
score = scorePreferences.getInt("score", 0);
scoreValue.setText(Integer.toString(score));
// get time and set text field
timePreferences = getSharedPreferences("time", 0);
time = timePreferences.getInt("time", 0);
timeValue.setText(Integer.toString(time) + " seconds");
// get highscore and set text field
highscorePreferences = getSharedPreferences("highscore", 0);
highscore = highscorePreferences.getInt("highscore", 0);
highscoreValue.setText(Integer.toString(highscore));
}
答案 0 :(得分:2)
看起来您对共享首选项使用相同的键,这就是值覆盖的原因。 我建议使用sqlite来存储最高分。
答案 1 :(得分:2)
应该这样:
if (score > scorePreferences.getInt("highscore", 0)...
......不像是:
if (score > highscorePreferences.getInt("highscore", 0)...
“highscore”键位于您的首选项中,名称相同。看起来您正在从“得分”偏好中读取该键。它不存在,因此始终使用默认值0。
答案 2 :(得分:2)
使用一个SharedPreferences对象。要保存,您可以这样做:
SharedPreferences prefs = getSharedPreferences("score", Context.MODE_PRIVATE);
int highscore = prefs.getInt("highscore", 0);
int hightime = prefs.getInt("hightime", 0);
if (score > highscore && time > hightime) {
SharedPreferences.Editor editor = prefs.editor();
editor.putInt("highscore", score);
editor.putInt("hightime", time);
editor.commit();
}
然后加载它,也使用一个SharedPreferences对象:
private void load() {
SharedPreferences prefs = getSharedPreferences("score", Context.MODE_PRIVATE);
score = prefs.getInt("score", 0);
scoreValue.setText(Integer.toString(score));
time = prefs.getInt("time", 0);
timeValue.setText(Integer.toString(time) + " seconds");
highscore = prefs.getInt("highscore", 0);
highscoreValue.setText(Integer.toString(highscore));
}
注意:
使用prefs文件名和变量的密钥是个好主意,这样可以避免在保存/检索变量时容易出现错字错误,例如。
public static final String PREFS_NAME = "score";
public static final String KEY_HIGHSCORE = "highscore";
public static final String KEY_HIGHTIME = "hightime";
然后使用它
SharedPreferences prefs = getSharedPreferences(ClassNameWhereItsDeclared.PREFS_NAME, Context.MODE_PRIVATE);
editor.putInt(ClassNameWhereItsDeclared.KEY_HIGHSCORE, score);
等。