0

How would I go about validating a user entered an Integer and not Nothing. The user must enter something into the editText and it must a be an integer. How do I go about validating it.

I have this:

int age = Integer.parseInt(editAge.getText().toString());

if(editAge.getText().toString().equals("")){
      Toast messsage please try again
}else they are good to go

I do not know how to test if the edit text is blank or a string is entered

  • In addition to the answer given, you can also limit text entered to just numbers, see here: http://stackoverflow.com/questions/5200689/android-limiting-edittext-to-numbers – Daniel Nugent Jun 21 '15 at 02:39

2 Answers2

1

Use Integer.parseInt() to convert the entered string into an integer. If it succeeds then it is an integer. If it doesn't, it is not an integer.

String text = editAge.getText().toString();
try {
   int num = Integer.parseInt(text);
   Log.d("",num+" is a number");
   // Good to go.
} catch (NumberFormatException e) {
   // Toast message. Please try again.
}
Bidhan
  • 10,607
  • 3
  • 39
  • 50
0

Instead of validating, you can use input type like below. With this, user can enter number only

<EditText
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:inputType="numberDecimal"
   android:numeric="integer"/>
Phuc Tran
  • 7,555
  • 1
  • 39
  • 27