tags:

views:

94

answers:

2

hi,

Here's the problem I'm facing : In my application I have several preferences stored in sharedPreferences that record different settings of the application. These are some strings. Because I want the application to start with some default values for these settings , in onCreate I construct a "Setting" object for each setting in which I check to see if the sharedPreference associated is null and if it is so I put the default Value in the sharedPreference.

Setting(int setting, String default)
{
    storedPref=sharedPref.getString(getText(setting),null);
    if(storedPref==null)
    {
      SharedPreferences.Editor edit=sharedPred.edit()
      edit.putString(getText(setting),default);
      edit.comit
    }
}

The views associate to these settings are ListPreferences (). When first opened the application , they are supposed to display a list of options , in which the selected one is the default ,but it happens sometimes no options is selected , not even the default one, which is not intended.

The listPreferences are constructed in xml , by setting an array to the "entries tag" and to the "values tag" . I'm not really sure , what should I pass to the constructor of the Setting object for the default , a member of the entries array , or a something from the values one !!! If I pass a member of the entries some will Listpreferences will have the expected behaviour and some will have the one described above. If I do otherwise and pass something from the values array , the same thing happens ! Has anyone any ideea why this strange behaviour ?

A: 

Since the second parameter of SharedPreferences.getString() is the default value that will be returned if the key is not present, you could just as easily write

Setting(int setting, String default)
{
  storedPref=sharedPref.getString(getText(setting),default);
}
Jim Blackler
Yes, but than doesn't mean that the default will be saved , which is what I need.
rantravee
+1  A: 

You should check out the preferences file, and recognize the key and format is used by our ListPreference, then you use the same key value pair in your SharedPreferences.Editor

you will find your prefs files in the following folder

/data/data/com.your.package/shared_prefs/

you get there by running in console:

adb shell
cd /data/data/com.your.package/shared_prefs/
ls
Pentium10
What do you mean by Key and format ?
rantravee
if you mean the setting key and the format as in value (K,V) , than I use the same parameters when I save the default
rantravee