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?
Asked
Active
Viewed 1,134 times
-1
-
http://developer.android.com/guide/topics/data/data-storage.html#pref – Phantômaxx Feb 26 '15 at 17:32
1 Answers
3
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";

Paul Woitaschek
- 6,717
- 5
- 33
- 52
-
1`this` parameter inside `PreferenceManager.getDefaultSharedPreferences()` method is the context of the application. Also, the String used for saving / getting a preference should be a `public static final String` field inside the class (to avoid spelling bugs) – Nino DELCEY Feb 26 '15 at 17:33