1

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.

1
  • There is a decent tutorial from Google, what impression did you get from it? Commented Jul 23, 2015 at 5:54

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

It's nice to suggest apply and singleton class. +1
Thank you. I think it's one of the best options if you are to modify your saved value lots of times
Thank you, still learning so I'll try this and let you know how it goes. Could you expand on your example though? How you would set default value, then call, add to, and save to later be called again. (Hope that made sense)
0

Yes , "If you have a relatively small collection of key-values that you'd like to save, you should use the SharedPreferences", has been noticed in Google document.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.