0

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

As the doc says for getPreferences:

Retrieve a SharedPreferences object for accessing preferences that are private to this activity. This simply calls the underlying getSharedPreferences(String, int) method by passing in this activity's class name as the preferences name.

getDefaultSharedPreferences:

Gets a SharedPreferences instance that points to the default file that is used by the preference framework in the given context.

So the the two methods return different preference object, this is why you get the default values.

Change the getPreferences(MODE_PRIVATE) to PreferenceManager.getDefaultSharedPreferences().

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.