Search code examples
javaandroidpreference

How to validate an EditTextPreference value for a specific int range


I want to validate an EditTextPreference value to be inside a specific int range (lets say 1 to 22). The only part that I could validate was the inputType (number only) with the following xml declaration in the prefs.xml file.

android:inputType="number"

The second thing that I did is to write the following code in the ListSettings activity.

public class ListSettings extends PreferenceActivity implements OnSharedPreferenceChangeListener{

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.prefs);
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    sp.registerOnSharedPreferenceChangeListener(this);
}
 public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
        String value = sp.getString(key, null);
        int intZoomValue = Integer.parseInt(value);
        if (intZoomValue < 1 || intZoomValue > 22) {
            Intent intent = new Intent().setClass(this, dialog.class);
            // I want to call the dialog activity here...
        }

  }

and the dialog.class is the following:

public class dialog extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  AlertDialog.Builder builder = new AlertDialog.Builder(this);
  builder.setMessage("Please enter a value between 1-22!");
  builder.setCancelable(true);

  AlertDialog alert = builder.create();
  alert.show();
  }
}

What I want to achieve is to call the dialog.class (the alert dialog box) whenever the user enters a value not in the range 1-22.

I can't really understand how to validate with the proper way.


Solution

  • It might be more user-friendly to just clamp the value to the permitted range if an invalid value is entered, and notify the user with a Toast that you have done so.

    If your range is small, such as 1-22, then you may even consider using a Spinner instead of an EditText so that the user can't enter an invalid value in the first place.