Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you validate the format and values of EditTextPreference entered in Android 2.1?

Does anyone have sample code to validate user entered text in preferences? For example, I have a EditTextPreference for user to enter an email address. I'd like to validate the format of email address entered and pop up an alert dialog if the format isn't correct. Anyone have any sample code for this? Thanks

like image 833
Bryan C Avatar asked Mar 29 '10 00:03

Bryan C


1 Answers

Your question was an early google hit when I was trying to do the same thing, so hopefully this helps someone. Here's something I hacked together today that demonstrates OnPreferenceChangeListener, thus allowing you to stop invalid changes.

in your fragment:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);

        Your_Pref = (EditTextPreference) getPreferenceScreen().findPreference("Your_Pref");

        Your_Pref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                Boolean rtnval = true;
                if (Your_Test) {
                    final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                    builder.setTitle("Invalid Input");
                    builder.setMessage("Something's gone wrong...");
                    builder.setPositiveButton(android.R.string.ok, null);
                    builder.show();
                    rtnval = false;
                }
                return rtnval;
            }
        });
    }
like image 156
Aaron Avatar answered Oct 21 '22 08:10

Aaron