ilomambo
ilomambo

Reputation: 8350

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?

Upvotes: 5

Views: 857

Answers (3)

kjdion84
kjdion84

Reputation: 10064

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

Upvotes: 1

x-code
x-code

Reputation: 3000

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

Upvotes: 3

AmaJayJB
AmaJayJB

Reputation: 1463

You could use the editor: (http://developer.android.com/reference/android/content/SharedPreferences.html#edit()) which allows to make changes atomically and then call commit only if everything is right. I hope this helps.

Upvotes: 0

Related Questions