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!

Max
  • 739
  • 2
  • 8
  • 23
Hap
  • 556
  • 1
  • 6
  • 20
  • are you sure you are reading the same preferences file? – SERPRO Mar 06 '12 at 16:32
  • 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? – Hap Mar 06 '12 at 16:45
  • @SERPRO is there a problem because the xml is inside the xml directory? – Hap Mar 06 '12 at 16:47
  • 1
    have a look at this question. it might be useful for you http://stackoverflow.com/questions/5652682/android-preferences-what-is-the-difference – SERPRO Mar 06 '12 at 16:47

2 Answers2

17

change your code to:

 SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);   
 String mapTypeString = preferences.getString("map_type_pref_key", "DEFAULT");
ligi
  • 39,001
  • 44
  • 144
  • 244
  • 5
    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? – Hap Mar 06 '12 at 17:35
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();
AiOO
  • 53
  • 2
  • 2
    "But I am unable to retrieve the value the user selected." He wants to retrieve, not to change. – António Paulo Apr 08 '16 at 16:09
  • 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 – JFed-9 Mar 19 '20 at 23:17