The onSharedPreferenceChanged()
listener does not have a boolean type to return, as the onPreferenceChanged()
listener has.
So how can one reject a change after validation?
The only way that occurs to me is to keep all shared preferences stored in local variables and if the validation fails, restore the value from the local variable, if it passes update the local variable.
Is this doing double work? Is there a built-in mechanism for reject?
Is this doing double work?
I think so. If one part of the code is going to reject this change, why did another part of the code permit it?
Is there a built-in mechanism for reject?
The user input should be validated in onPreferenceChange
before it is committed. It looks like the purpose of onSharedPreferenceChanged
is not validation but to receive a read-only live update when a change has been committed.
Since other code could receive this callback and act on it, it's too late to validate during this callback.
Reference (the Preference javadoc):
This class provides the View to be displayed in the activity and associates with a SharedPreferences to store/retrieve the preference data
Basically you use setText
to return the value to default if it does not meet your requirements. Then you can show a Toast or whatever to inform the user of the issue.
Here is the solution:
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
if ("mypref".equals(key)) {
String value = sharedPreferences.getString(key, "");
try {
int v = Integer.parseInt(value);
// do whatever is needed
} catch (RuntimeException e) {
String deflt = ... # fetch default value
EditTextPreference p = (EditTextPreference) findPreference(key);
p.setText(def);
}
}
}
Credit: http://androidfromscratch.blogspot.ca/2010/11/validating-edittextpreference.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With