Why does preferences.getString("key", "DEFAULT") always return "DEFAULT"?

47,516

Solution 1

change your code to:

 SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);   
 String mapTypeString = preferences.getString("map_type_pref_key", "DEFAULT");

Solution 2

You have to commit the preferences after edit it.

SharedPreferences preferences = getSharedPreferences("user_preferences.xml", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("map_type_pref_key", "blah_blah");
editor.commit();
Share:
47,516
Hap
Author by

Hap

Hap is shy.

Updated on March 19, 2020

Comments

  • Hap
    Hap over 4 years

    I have user_preferences.xml in my XML directory. A PreferencesActivity uses this file to create the user preferences activity.. and that works. Whatever the user selects here persists. But I am unable to retrieve the value the user selected.

    When I use...

    SharedPreferences preferences = getSharedPreferences("user_preferences.xml", 0);    
    String mapTypeString = preferences.getString("map_type_pref_key", "DEFAULT");
    

    ... mapTypeString is always "DEFAULT".

    It seems like my user_preferences.xml is not found when I instantiate my SharedPreferences object. But, the PreferencesActivity finds it, of course. So, what am I missing?

    Many thanks!

  • Hap
    Hap over 12 years
    That works, thank you. But I am still a bit confused... I use another xml which also stores preferences in the same Activity. Why does getDefaultSharedPreferences give me user_preferences.xml and not the other, settings.xml?
  • António Paulo
    António Paulo about 8 years
    "But I am unable to retrieve the value the user selected." He wants to retrieve, not to change.
  • JFed-9
    JFed-9 over 4 years
    This could very well be the issue, if OP never set the value with a commit() or apply(), the data would never be retrievable, but it would need more clarification from the question