我已经设法让我的分数正确保存到SharedPreferences以及它保存到高分。然而,当检查之前的分数是否比保存的高分更好时,无论如何,它总是会保存它,我不知道为什么。使用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();
}
然后,它获取gameoveractivity和高分活动使用此代码阅读:
// 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));
}
分解你的第一行像这样你可以找出原因:'int currentHighScore = scorePreferences.getInt(“highscore”,0); int currentHighTime = timePreferences.getInt(“hightime”,0); Log.i(“分数”,currentHighScore +“”+ currentHighTime);如果(分数> currentHighScore && time> currentHighTime){' – Tenfour04
更好的时间更好? – Broak
顺便说一句,您不需要为每种类型的条目分开SharedPreferences文件。这就是为什么这些条目有键。 SharedPreferences很像一个HashMap。此外,由于您正在为每个共享首选项的实例使用成员变量,因此您不必在第一次在'onCreate'中执行操作后继续调用getSharedPreference。 – Tenfour04