10

I have PreferenceActivity with 2 fields.

  1. A URL
  2. Time in seconds

I need to validate the first one for a valid URL and the second for an integer value. How do I do it with standard means?

2 Answers 2

17

Here's some code implementing OnPreferenceChangeListener 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;
        }
    });
}
2
  • The new value of the field is held in an object called newValue. Use newValue.tostring for (Your_Test) Commented Feb 21, 2013 at 11:01
  • preference will not be saved if we use this. Commented Aug 19, 2013 at 7:36
3

You can use android:inputType attribute for these fields in the xml, this will display a keyboard to the user for entering the value in a specific format.

See more

http://developer.android.com/reference/android/text/InputType.html

But this do not guarantee that the URL will not be malformed. That you would need to check using regular expression in your submit handler.

1
  • 1
    Yeah. I made validation through onchangelistener and regexp matcher Commented Oct 5, 2011 at 15:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.