HighScore through SharedPreferences
-
Good night. Help me understand what I'm doing wrong. I want to make a record of the best account. But when I close the game, the data won't be kept. And as much as I do, when the game is closed in another classroom, it's the best score. Thank you very much.
public static final String APP_PREFERENCES = "file"; public static final String APP_PREFERENCES_NAME = "Score"; static SharedPreferences sharPre; static int score2 = 0; // ЛУЧШИЙ СЧЁТ
/ Game.iscore is just a score.
@Override protected final void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.lose);
sharPre = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);// копируй if(sharPre.contains(APP_PREFERENCES_NAME)) { // проверяем есть ли в файле запись score2 = sharPre.getInt(APP_PREFERENCES_NAME, 0); // Если запись есть, тогда загружаем из файла в переменную } else{ score2 = 0; // если нету, присваиваем 0 } if (Game.iscore > score2) { // если обычный счёт больше лучше счёта score2 = Game.iscore; // лучшему счёту присваиваем обычный SharedPreferences.Editor editor = sharPre.edit(); editor.putInt(APP_PREFERENCES_NAME, score2); editor.commit(); // эти 3 строчки записывают в файл значение переменной "score2" } else { // если счёт не больше лучшего if(sharPre.contains(APP_PREFERENCES_NAME)) { // проверяем наличие в файле счёта score2 = sharPre.getInt(APP_PREFERENCES_NAME, 0); // загружаем данные из файла в переменную score2 } else{ // если нету ничего в файле, присваиваем 0 score2 =0; } }
@Override
protected void onStop(){ // этот метод записывает в файл данные при выходе из игры.
super.onStop();
SharedPreferences.Editor editor = sharPre.edit();
editor.putInt(APP_PREFERENCES_NAME,score2);
editor.commit();
}
-
Code working. It's just because String was in the file first, and then int, the application came out. I just renamed every variable. So use it. I hope that helps someone else, and he won't spend so much time solving a problem that's basically not.