Reputation: 310
I'm using some activities in my project. One of them is extended from PreferenceActivity. I have a CheckBoxPreference and an EditTextPreference, I can get the values from all the other activities using:
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
pref = sharedPrefs.getString("edit_text_pref", "error");
but when I open my app the values must be set to default, therefore I'm using:
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().clear().commit();
in my main activity.
All should be ok, but if I try to get the preference before to set it from the preferences menu I get "error" and not the default value that I set in the xml preference file.
If i comment the getDefaultSharedPreferences
line it works fine but obviously when i open the app I get the old preferences.
How can i bypass this problem?
Upvotes: 1
Views: 11306
Reputation: 189
Take a look into http://developer.android.com/reference/android/preference/PreferenceManager.html#setDefaultValues%28android.content.Context,%20int,%20boolean%29
Yout must be using this setDefaultValues (Context context, int resId, boolean readAgain)
some thing like
PreferenceManager.setDefaultValues(this, R.xml.preference, false);
Take a good look at the note section in the parameters. This is concering read again Parameters
context
The context of the shared preferences.
resId
The resource ID of the preference XML file.
KEY_HAS_SET_DEFAULT_VALUES
in the default value shared preferences file is false). To attempt to set the default values again bypassing this check, set readAgain to true.getDefaultSharedPreferences(Context)
and clear it followed by a call to this method with this parameter set to trueSo I guess after clearing it you need to set it to default by passing the readAgain as true
something like
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().clear().commit();
PreferenceManager.setDefaultValues(this, R.xml.preference, true);
Upvotes: 5
Reputation: 310
well, I tought the "error" was the value used if there was an error reading the value and not if the value was not set!!
Thank you it should be work, I'm going to try
Upvotes: 0
Reputation: 1967
You are receiving the default value itself, i.e, "error" because with Preferences, when you get the value of any preference then you need to specify a value that is to be returned if the preference is not set before. In your case, as you are setting the default value to "error" in here pref = sharedPrefs.getString("edit_text_pref", "error");
so thats what you get as the default value.
Upvotes: 2