I got a PreferenceActivity
. When a user is changing a preference, I want to save some additional preferences so inside the OnPreferencesChange
method, I got something like this:
if(p.getKey().equals("mykey")) //there is no issue with this if. it enters and get inside to the commit command
{
getPreferences(MODE_PRIVATE).edit().putString("otherKey","value").commit();
return true;
}
I also got a Service (which is of course a different class than that of the PreferenceActivity) in which I want to read the preferences. So I'm doing something like this:
sp = PreferenceManager.getDefaultSharedPreferences();
String val1 = dsp.getString("myKey","default1");
String val2 = dsp.getString("otherKey","default2");
I get the correct value of "mykey", but always get "default2" for the "otherKey". Why is that? Could it be that the Service get the wrong SharedPreference?
Instead of
getPreferences(MODE_PRIVATE).edit().putString("otherKey","value").commit();
do:
PreferenceManager.getDefaultSharedPreferences( this ).edit().putString("otherKey","value").commit();
getPreferences()
returns a "SharedPreferences object for accessing preferences that are private to this activity", according to the documentation.