Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate preferences. Android

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?

like image 363
Jevgeni Smirnov Avatar asked Sep 27 '11 04:09

Jevgeni Smirnov


People also ask

What are preferences Android?

When specifying a preference hierarchy in XML, each element can point to a subclass of Preference , similar to the view hierarchy and layouts. This class contains a key that will be used as the key into the SharedPreferences . It is up to the subclass to decide how to store the value.

How do I set custom preferences on Android?

It's still possible to customise the appearance of a Preference item though. In your XML you have to declare the root element as android:id="@android:id/widget_frame , and then declare TextView as android:title and android:summary . You can then declare other elements you want to appear in the layout.

Where can I find preferences in Android Studio?

From the menu bar, click File > Settings (on macOS, click Android Studio > Preferences).

What is PreferenceScreen?

androidx.preference.PreferenceScreen. A top-level container that represents a settings screen. This is the root component of your Preference hierarchy. A PreferenceFragmentCompat points to an instance of this class to show the preferences. To instantiate this class, use PreferenceManager.


2 Answers

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;
        }
    });
}
like image 158
Aaron Avatar answered Sep 27 '22 23:09

Aaron


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.

like image 24
Rahul Choudhary Avatar answered Sep 27 '22 22:09

Rahul Choudhary