How to reject a change in the onSharedPreferenceChanged () listener

The listener onSharedPreferenceChanged()

does not have a boolean return type like the listener does onPreferenceChanged()

.

So how can you reject a change after review?

The only way that comes up for me is to keep all the shared settings stored in local variables, and if the check fails, restore the value from the local variable if it passes the update to the local variable.

Is this a double job? Is there a built-in rejection mechanism?

+3


source to share


3 answers


Is this a double job?

I think so. If one part of the code is going to reject this change, why does another part of the code allow it?

Is there a built-in mechanism for rejection?

User input must be confirmed onPreferenceChange

before committing. It looks like the goal is onSharedPreferenceChanged

not validation, but to get the current read-only update when the change was made.



Since other code could have received this callback and act on it, it is too late to be validated during this callback.

Link (javadoc preference):

This class provides a view to be displayed in the action and communicates with SharedPreferences to store / retrieve preference data.

+2


source


You can use an editor: ( http://developer.android.com/reference/android/content/SharedPreferences.html#edit () ), which allows you to make changes atomically and then only trigger a commit if everything is correct. Hope this helps.



0


source


This issue is currently working.

Here's 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

You mainly use setText

to return the default if it doesn't suit your requirements. You can then show a Toast or whatever to inform the user of the problem.

0


source







All Articles