I have in preferences.xml following EditTextPreference:
<EditTextPreference
android:name="@string/pref_test"
android:defaultValue="0.6"
android:inputType="numberDecimal"
android:key="editTestPref"
android:maxLength="5"
android:summary=""
android:title="@string/pref_test" />
In one of my activities I read the value.
But the problem is if the user enters nothing (“”), my app crashes. Sure I could do a if statement in the activity to check if its empty string, but I want to do following:
In Preferences.java I get changes of the preferenceEditText. There I want to set a default value if the user enters “”:
if (preference.getKey().equals("editTestPref")) {
if(newValue.equals(""))
{
final SharedPreferences.Editor prefsEditor = prefs.edit();
prefsEditor.putString("editTestPref", "1");
prefsEditor.commit();
summary = "0.6"; // to update the summary of preference
}
else
{
summary= (String) newValue;
}
}
I also tried this code:
SharedPreferences customSharedPreference = getSharedPreferences(
"myCustomSharedPrefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = customSharedPreference
.edit();
editor.putString("editTestPref", "1");
editor.commit();
Both do not work, they do not update the sharedPreference value. It is still “”.
Implement
SharedPreferences.OnSharedPreferenceChangeListenerlike so:The method is called when the user changed the preferences value, and checks if he entered an empty string. If so, the value is replaced by your default value.