简体   繁体   中英

Android/Java - Using SharedPreferences to make, edit, add to a number value

I want to store a number value, retrieve it, add to it, save and repeat to add to it as needed. Should I be using SharedPreferences?

My app is calling a players score, in game, adding to it and displaying it again as needed. I need this score to be displayed on several activities.

Yes, you can use SharedPreferences for this task.

Even if you read/write your value many times, if you use apply() method, not commit(), the SP API will write the value to the disk asynchronously.

However, if you read the value before it was written on disk, the SP API will give you the value from the memory, thus making it very efficiently to use.

I advice you to make an utility singleton class with public methods like

  • public void setValue(final int value);

  • public void increaseValue(final int addition);

  • public int readValue();

Later edit: I don't believe I had an argument for making the class a SingleTon. The point is: get the SharedPreference instance only ONCE in the constructor using the ApplicationContext (not the Activity context that you would pass as an argument to the getInstance method) so that it remains valid for the entire life of your app.

This way, you avoid making costly (like getting the SharedPreference instance) in each of the methods (write/read).

This is why, in this case, I advice for SingleTon vs public static methods

是的,“在文档中,如果您要保存的键值集合相对较小,则应该使用SharedPreferences”。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM