SharedPreferences android code example
Example 1: android sharedpreferences
SharedPreferences sharedPref = getSharedPreferences(PREFERENCES_FILENAME, MODE_PRIVATE);
String value = sharedPref.getString(PREFERENCE_KEY, null);
sharedPref.edit()
.putString(PREFERENCE_KEY, value)
.apply();
Example 2: android save int
public void saveInt(int val, String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mainActivity);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(key, val);
editor.apply();
}
public int getInt(String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mainActivity);
int val = prefs.getInt(key, 0);
return val;
}
Example 3: android sharedpreferences
SharedPreferences sharedPref = getSharedPreferences("name", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("key", "Value");
editor.commit();
Example 4: get preference value android
boolean mBoolean = PreferenceManager.getDefaultSharedPreferences(yourContext).getBoolean(key, defaultValue);
Example 5: refresh sharedpreferences going back java
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
Example 6: store data in sharedpreferences android
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.apply();