Reputation: 87
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
Upvotes: 0
Views: 107
Reputation: 10697
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.
}
Upvotes: 1
Reputation: 8083
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"/>
Upvotes: 0