Saturday, August 10, 2019

java - How to get integers saved into SharedPreferences




I have made a food calculator, which calculates calories (from food types) and weight (based on user input using EditText) and displays these in a TextView. How would I then take the value displayed in the textView and save it into an SharedPreference?


Answer



To save the value, you write it to the SharedPreferences.



private static final String VALUE_TAG = "myTag";
Context c = this; //this for Activity. For Fragment use getActivity();



You always assign a value to a key, I called "myKey"



SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(c);
SharedPreferences.Editor editor = sp.edit();
editor.putInt(VALUE_TAG, 5);
editor.apply();


And to retrieve it:




int defaultValue = 42;
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(c);
int retrievedValue = sp.getInt(VALUE_TAG , defaultValue);


Where the 42 is the value returned if there is no value with the key "myKey";


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...