Why does preferences.getString(“key”, “DEFAULT”) always return “DEFAULT”?
-
08-12-2019 - |
Question
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!
Solution
change your code to:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String mapTypeString = preferences.getString("map_type_pref_key", "DEFAULT");
OTHER TIPS
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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow