Android – Storing/retrieving strings with shared preferences

To save to preferences:

PreferenceManager.getDefaultSharedPreferences(context).edit().putString("MYLABEL", "myStringToSave").apply();  

To get a stored preference:

PreferenceManager.getDefaultSharedPreferences(context).getString("MYLABEL", "defaultStringIfNothingFound"); 

Where context is your Context.


If you are getting multiple values, it may be more efficient to reuse the same instance.

 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
 String myStrValue = prefs.getString("MYSTRLABEL", "defaultStringIfNothingFound");
 Boolean myBoolValue = prefs.getBoolean("MYBOOLLABEL", false);
 int myIntValue = prefs.getInt("MYINTLABEL", 1);

And if you are saving multiple values:

Editor prefEditor = PreferenceManager.getDefaultSharedPreferences(context).edit();
prefEditor.putString("MYSTRLABEL", "myStringToSave");
prefEditor.putBoolean("MYBOOLLABEL", true);
prefEditor.putInt("MYINTLABEL", 99);
prefEditor.apply();  

Note: Saving with apply() is better than using commit(). The only time you need commit() is if you require the return value, which is very rare.

private static final String PREFS_NAME = "preferenceName";

public static boolean setPreference(Context context, String key, String value) {
    SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString(key, value);
    return editor.commit();
}

public static String getPreference(Context context, String key) {
    SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    return settings.getString(key, "defaultValue");
}

I solved it!
It didn’t work when I called the methods from within the class! I had to call it from another class for some reason, and write “classname.this” as Context parameter.
Here’s the final working:

SharedPreferences settings = ctx.getSharedPreferences(PREFS_NAME, 0);
    settings = ctx.getSharedPreferences(PREFS_NAME, 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString(tal, pathtilsave);
     editor.commit(); 

Leave a Comment