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?
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.