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

Hap picture Hap · Mar 6, 2012 · Viewed 45.4k times · Source

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!

Answer

ligi picture ligi · Mar 6, 2012

change your code to:

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