android shared preferences example for high scores?

牧云@^-^@ 提交于 2019-12-05 16:53:34

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.

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!