我已經設法讓我的分數正確保存到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