Saturday 10 August 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...