How to determine if an input in EditText is an integer?

59,190

Solution 1

Update:

You can control the EditText to only accept numbers

<TextView 
.
.
.
android:inputType="number"
/>

or check it programmatically

In Kotlin

val number = editText123.text.toString().toIntOrNull() 
val isInteger = number != null

In Java

String text = editText123.getText().toString();
try {
   int num = Integer.parseInt(text);
   Log.i("",num+" is a number");
} catch (NumberFormatException e) {
   Log.i("",text+" is not a number");
}

Solution 2

Since API level 1, Android provides an helper method to do just that (no need to use regex or catching exception) : TextUtils.isDigitsOnly(CharSequence str)

boolean digitsOnly = TextUtils.isDigitsOnly(editText.getText());

Note that this method returns true with empty String : Issue 24965

Solution 3

If you whant EditText accept only numbers you cant specify android:inputType="number" in layout file.

Solution 4

You can use TextWatcher for EditText to get value of every change in EditText.You need to add interface of TextWatcher in your Activity.

 mEditText.addTextChangedListener(Your Class Name.this);

on in method of TextWatcher

     @Override
public void afterTextChanged(Editable s) {
    Log.v("Log_tag", "After TextChanged" + s.toString());

}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
        int after) {
    Log.i("Log_tag", "Before TextChanged" + s.toString());

}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    Log.e("Log_tag", "ontext Changed" + s.toString());
    //you can match here s with number or integer 
             if(isNumeric( s.toString())){
                      //it is number     
               }
    }


 public static boolean isNumeric(String str)
 {
    return str.matches("-?\\d+(.\\d+)?");
  }

Solution 5

Following code can be used to determine digits,

boolean isDigits = TextUtils.isDigitsOnly(edtDigits.getText().toString());

However since this method returns true with empty String as well so you can put a validation for empty string as follows,

public boolean isDigits(String number){ 
   if(!TextUtils.isEmpty(number)){
       return TextUtils.isDigitsOnly(number);
   }else{
       return false;
   }
}
Share:
59,190
Yansuck
Author by

Yansuck

Updated on July 18, 2022

Comments

  • Yansuck
    Yansuck almost 2 years

    Hi I'm a newbie in Android Programming.

    I'm trying to build an activity which includes an edittext field and a button. When user type in an integer, the button will lead them to the next activity. However I do not if there's a way to check the type of user's input.

    Anyone can help me? Thank you very much!