-3

I have a single Integer in my app that the user can click a button to add or subtract to. I want the Integer to keep it's value when the user exits and reopens the app. I have checked out SharedPrefrences and it was complicated and didn't make sense to me.

rayan
  • 5
  • 1
  • 1
    What didn't you understand in using SharedPreferences?! You have specific methods for reading and writing several types of key/value pairs. i.e.: `getInt()` and `putInt()`. When writing, you have to `apply()` or `commit()` the changes (the difference is that the former is asynchronous and the latter is synchronous). So, as usual, create the object, use it, and finally close it. – Phantômaxx Feb 25 '17 at 09:54
  • Possible duplicate of [Android Shared preferences example](http://stackoverflow.com/questions/23024831/android-shared-preferences-example) – Abhishek Jain Feb 25 '17 at 10:05

2 Answers2

1

I have checked out SharedPrefrences and it was complicated and didn't make sense to me.

you have to handle the fact that there are not to many options...

  1. store the info in the preferences
  2. store the info in a DB you can
  3. push that data into a server and hold it back

if you only need an integer value, then SharedPref is the most easy way to go....

how to write:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();

how to read it back:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);

official doc is here

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

There's few ways to store persistent information in an Android App

  1. SharedPrefrences; this is the easiest way you can think off, without asking user for storage/network permissions

usage e.g.:-

PreferenceManager.getDefaultSharedPreferences(context).getInt("X", 1); // to retrieve 
PreferenceManager.getDefaultSharedPreferences(context).putInt("X", 1); // to store 
  1. File storage (internal/external); this is as easy as saving a text file in the internal or external storage, but does require user permission

  2. SQLLite / other internal or external database service; this is as complicated as it gets, but this is more flexible

xxfast
  • 697
  • 5
  • 14