android shared preferences example for high scores?

11,378

If you want to use shared preferences the problem is that you can't really store a list or something like that. Shared preferences only supports boolean, float, int, String, long and Set.

So your best choice is the Set. There you can convert each value of your highscore to a string, add it to a Set and then store this set in the shared preferences.

During startup of your application you can retrieve the set, convert the Strings back to ints or whatever you use to represent the highscore.

See for example this method:

http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#putStringSet(java.lang.String, java.util.Set)

EDIT

As MisterSqounk pointed out, Set is only available since API Level 11. So if you're coding for below, I would suggest to store the values directly as ints using keys like for example highscore1, highscore2, ... When retrieving the highscore values you could iterate over all keys and using SharedPreferences#contains(String key) to check whether a value is available.

Share:
11,378
user560571
Author by

user560571

Updated on June 08, 2022

Comments

  • user560571
    user560571 about 2 years

    Hi I was wondering is there any simple example of implementing a high score list using shared preferences? ie have pre determined high scores at the start and then update the list dependingt on the score a user gets?