android shared preferences example for high scores

2019-05-06 06:35发布

问题:

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?

回答1:

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.



回答2:

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



回答3:

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.