how to use sharedpreferences in android code example
Example 1: android sharedpreferences
// load file
SharedPreferences sharedPref = getSharedPreferences(PREFERENCES_FILENAME, MODE_PRIVATE);
// read value
String value = sharedPref.getString(PREFERENCE_KEY, null);
// write value
sharedPref.edit()
.putString(PREFERENCE_KEY, value)
.apply();
Example 2: android sharedpreferences
SharedPreferences sharedPref = getSharedPreferences("name", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("key", "Value");
editor.commit();
Example 3: get preference value android
boolean mBoolean = PreferenceManager.getDefaultSharedPreferences(yourContext).getBoolean(key, defaultValue); //getBoolean will return defaultValue is key isn't found
//you can also use getInt, getFloat, getLong, getString, getStringSet and change the variable type, of course
Example 4: refresh sharedpreferences going back java
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
Example 5: store data in sharedpreferences android
// MY_PREFS_NAME - a static String variable like:
//public static final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.apply();