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

前端 未结 5 1326
清歌不尽
清歌不尽 2020-12-20 07:57

I\'m building an application for receiving grades and I want to make sure that the Edit Texts are not empty and the values are less or equal to 100 I wrote this line but it

相关标签:
5条回答
  • 2020-12-20 08:33

    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

    0 讨论(0)
  • 2020-12-20 08:37

    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
    }
    
    0 讨论(0)
  • 2020-12-20 08:45

    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 :)

    0 讨论(0)
  • 2020-12-20 08:53

    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
    } 
    
    0 讨论(0)
  • 2020-12-20 08:58

    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 )
         {
    
         }
    }
    
    0 讨论(0)
提交回复
热议问题