Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 410
Hap Avatar asked Mar 06 '12 16:03

Hap


People also ask

Where are Android preferences stored?

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() .

What is shared preferences Android?

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.

How to use shared preferences?

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.


2 Answers

change your code to:

 SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);   
 String mapTypeString = preferences.getString("map_type_pref_key", "DEFAULT");
like image 88
ligi Avatar answered Oct 19 '22 21:10

ligi


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();
like image 2
AiOO Avatar answered Oct 19 '22 23:10

AiOO