Recently I am developing a simple android game. For the scoring part, I have on many websites that shared preferences are best to save the high score. Now, what if I need to sav
To save your scores you can do something like this:
// prepare the data: put the String values of the scores of the first 3 users
// in one String array for each level
String[] firstLevelHighscores = new String[] {
firstUserLevel1Score, secondUserLevel1Score, thirdUserLevel1Score
};
String[] secondLevelHighscores = new String[] {
firstUserLevel2Score, secondUserLevel2Score, thirdUserLevel2Score
};
String[] thirdLevelHighscores = new String[] {
firstUserLevel3Score, secondUserLevel3Score, thirdUserLevel3Score
};
// now save them in SharedPreferences
SharedPreferences sharedPref = getSharedPreferences("LevelScores",
Context.MODE_PRIVATE);
Editor editor = sharedPref.edit();
editor.putStringSet("level1", firstLevelHighscores);
editor.putStringSet("level2", secondLevelHighscores);
editor.putStringSet("level3", thirdLevelHighscores);
Note that you can put even more user's scores into the String array. And if you need to save scores for more levels, you simply create more arrays.
To retrieve the saved data from SharedPreferences, you do it like this:
SharedPreferences sharedPref = getSharedPreferences("LevelScores",
Context.MODE_PRIVATE);
String[] firstLevelHighscores = sharedPref.getStringSet("level1", null);
String[] secondLevelHighscores = sharedPref.getStringSet("level2", null);
String[] thirdLevelHighscores = sharedPref.getStringSet("level3", null);
I assume you're able to convert int to String and vice versa. Hope it works for you this way.