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!
Android stores Shared Preferences settings as XML file in shared_prefs folder under DATA/data/{application package} directory. The DATA folder can be obtained by calling Environment. getDataDirectory() .
A SharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them. Each SharedPreferences file is managed by the framework and can be private or shared. This page shows you how to use the SharedPreferences APIs to store and retrieve simple values.
Shared Preferences allow you to save and retrieve data in the form of key,value pair. In order to use shared preferences, you have to call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences.
change your code to:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String mapTypeString = preferences.getString("map_type_pref_key", "DEFAULT");
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With