Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reject a change in onSharedPreferenceChanged() listener

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?

like image 992
ilomambo Avatar asked Oct 21 '22 00:10

ilomambo


2 Answers

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

like image 62
x-code Avatar answered Oct 23 '22 00:10

x-code


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

like image 22
kjdion84 Avatar answered Oct 23 '22 01:10

kjdion84