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