-2

I have three EditText controls and I need to make sure that each is the correct number input.

The first has to be a number between 0 and 23

The second has to be a number between 0 and 59

And the third has to be a number between 0 and 1500

I saw someone make a post about an easy EditText validation using setError, example:

EditText firstName = (EditText)findViewById(R.id.first_name);
if (firstName.getText().toString().length() == 0) 
     firstName.setError("First name is required!");

So is there an easy way to do it like above, but making sure a number isn't > 23, 59, or 1500 (individually)?

Smurfling
  • 99
  • 1
  • 2
  • 11
  • 1
    have a good answers here : [Is there any way to define a min and max value for edittext in android?](http://stackoverflow.com/a/14212734/1520438) – Danh DC Dec 17 '15 at 04:15

4 Answers4

0

Integer.parseInt(String s)can convert string to integer.Then, you validate it with if, else.

However, the input may not be an integer, and you have to set android:numeric="integer" in <EditText /> tag in the .xml file. Be careful about this, if the input string is not integer, Integer.parseInt() will throw an exception, which will cause a crash.

0

You want to make sure you're performing some error checking since the value is coming from the user. Try something like this:

EditText firstText = (EditText) findViewById(R.id.first);
try
{
    long firstVal = Long.parseLong(firstText.getText());
    if (firstVal < 0 || firstVal > 23)
        firstText.setError("The value must be between 0 and 23!");
}
catch (NumberFormatException e)
{
    firstText.setError("Enter an integer value!");
} 

// very similar for your remaining cases
wickstopher
  • 981
  • 6
  • 18
0
String value = firstName.getText().toString();
int  int_value = Integer.parseInt(value);
if (firstName.getText().toString().length() != 0) 
    if (int_value < 1500) {  
    // do what you want  
    }
    else if (int_value < 59) {
    // do what you want 
    }
    else if (int_value < 23) {
    // do what you want 
    } 
}else {
    firstName.setError("First name is required!");
}
sud
  • 505
  • 1
  • 4
  • 12
0
EditText firstEditText = (EditText)findViewById(R.id.first_edit_text);
EditText secondEditText = (EditText)findViewById(R.id.second_edit_text);
EditText thirdEditText= (EditText)findViewById(R.id.third_edit_text);
int value;

value = Integer.parseInt(firstEditText .getText().toString());
if (! value > 0 && value < 23) 
     firstEditText.setError("Error");

value = Integer.parseInt(secondEditText .getText().toString());
if (! value > 0 && value < 59) 
     secondEditText.setError("Error");

value = Integer.parseInt(thirdEditText.getText().toString());
if (! value > 0 && value < 1500) 
     thirdEditText.setError("Error");
cw fei
  • 1,534
  • 1
  • 15
  • 33