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

2

11

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!

Parr answered 6/3, 2012 at 16:30 Comment(4)
are you sure you are reading the same preferences file?Sian
In onCreate() in my PreferenceActivity, I use addPreferencesFromResource(R.xml.user_preferences); So maybe I need to point to the file differently when I create the SharedPreferences object?Parr
@Sian is there a problem because the xml is inside the xml directory?Parr
have a look at this question. it might be useful for you #5653182Sian
G
17

change your code to:

 SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);   
 String mapTypeString = preferences.getString("map_type_pref_key", "DEFAULT");
Grad answered 6/3, 2012 at 16:58 Comment(1)
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?Parr
S
1

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();
Screech answered 1/8, 2014 at 7:5 Comment(2)
"But I am unable to retrieve the value the user selected." He wants to retrieve, not to change.Reinstate
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 questionTrinitroglycerin

© 2022 - 2024 — McMap. All rights reserved.