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?
3 Answers
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.

- 51,941
- 35
- 152
- 200
-
3String Sets were introduced to SharedPreferences in Android v3.0 so not available before that. – Squonk Mar 21 '11 at 23:06
-
1@MisterSquonk Thnaks. That makes the solution more complicaed. But the OP didn't mentioned an API level. But I edited the answer so that it works for all API levels. – RoflcoptrException Mar 21 '11 at 23:11
-
If the list is static then you can use a `ListPreference` item type in your preferences screen for that purpose - this just saved the position of the selected item. You can also still use dynamic lists, just store the ID of the selected item in your preferences and your list in a database. – Joseph Earl Mar 21 '11 at 23:12
-
@Joseph Earl I wasn't able to find your ListPreference in the API. Could you provide a link? – RoflcoptrException Mar 21 '11 at 23:14
-
Sure: http://developer.android.com/reference/android/preference/ListPreference.html – Joseph Earl Mar 22 '11 at 00:35
Sometime ago, I implemented a library to use MEMDISKCACHE & SHAREDPREF as GENERIC_STORE You can even store/retrieve Serializable java objects. E.g. to meet your req, just create a custom Serializable Java object, then you are ready to go.
I'm using this in my apps already (even for massive facebook photo data), works pretty well and acts like abstraction layer.
here is the source, if anyone is interested. https://github.com/wareninja/generic-store-for-android

- 9,313
- 3
- 32
- 43
If you're still looking for a solution, Swarm's Leaderboards system looks like a good match. Provides a simple solution for adding customizable leaderboards to games, and is pretty easy to work with.

- 396
- 2
- 6