Check if an Edit Text that only accepts number is not empty and the number is equal or less than 100

自闭症网瘾萝莉.ら 提交于 2019-11-29 12:47:05

In your xml where you have declared edittext make sure that you put the following attribute in edittext element

android:inputType="number"

And change above code to this :

 if(editText.getText().toString().trim().isEmpty() || Integer.parseInt(editText.gettext().toString()) > 100 )
    {
    //Error message for example
    } 

you first need to check if text is not empty

First You Put In Your XML EditText Input Type=Number

Then Write This Code

If(edittext.getString().toString().Trim().lenght()>0)
{
     If(Integer.parseInt(editText.gettext().toString()) <= 100 )
     {

     }
}

You only have to switch the 2nd ans 1st expressions of the if. Because when the program runs it checks firstly the 1st expression and then the 2nd.

So... when you don't have any value on the editText the getText().toString() return this "" and its impossible to parse to Int that value so you have to check first the length() and after that check if the number is bigger than 100

if(editText.getText().toString().trim().isEmpty() || Integer.parseInt(editText.gettext().toString()) > 100 )
{
//Error message for example
} 

If you want to control what digit should enter use android:digits=""

android:inputType="number" enforce to open number type keyboard still user can press other char like "#,." than may cause NumberFormatException

<EditText
    android:inputType="number"
    android:digits="0123456789"
/>

android:digits="0123456789" only accepts 0123456789 in EditText, not any other char

Before converting any string integer you must check if it is empty

String strNumber=editText.getText().toString().trim();
 if(TextUtils.isEmpty(strNumber) || Integer.parseInt(strNumber)>100){
   // show your error message
}

Your logcat states that you are entering a String where the code requires a Integer.

Caused by: java.lang.NumberFormatException:

What i would suggest is store the EditText value in a different String and then check typecast it into Integer, many a times the compiler gets confused there.

Hope this helps :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!