android – How to determine if an input in EditText is an integer?-ThrowExceptions

Exception or error:

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!

How to solve:

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");
}

###

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

###

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

###

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+)?");
  }

###

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;
   }
}

###

Try this solution.

You need to add the properties android:nextFocusDown="@+id/nextedittext_id" and
android:singleLine="true" in your edittexts.

For example:

<EditText
        android:id="@+id/ed1"
        android:layout_width="200dp"
        android:nextFocusDown="@+id/ed2"
         android:singleLine="true"
        android:layout_height="wrap_content" />


 <EditText
        android:id="@+id/ed2"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:layout_below="@+id/ed1" />

And add the following code in your activity:

 editText1.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String value=s.toString();
                    if(isNumeric(value)){
                        if(Integer.parseInt(value)>=100){
                            editText1.setFocusableInTouchMode(true);
                            editText1.setFocusable(false);
                        }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        editText2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                editText1.setFocusableInTouchMode(true);
                editText1.setFocusable(true);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

isNumeric method is as same as above:

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

###

I found a much cleaner solution,which checks if the string is any type of number including integer, float, long or double.

import java.math.BigDecimal;

Boolean isNumber;

try {
    BigDecimal n = new BigDecimal(theStingToCheck);
    isNumber = true;
} catch (Exception e) {
    isNumber = false;
}

Leave a Reply

Your email address will not be published. Required fields are marked *