Skip to content
Advertisement

Android : Convert CharSequence to Int in Java

I’m confused on how can I convert CharSequence to int , I just want to set visibility of textfield when the inputted amount of edt_nma_amount is >=100

What I tried to convert it

int number = Integer.parseInt(s.toString());

but it returns me an error It crashes my app because the number is like string “”

java.lang.NumberFormatException: For input string: ""

java

 public void nmaAmount(){
    edt_nma_amount.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }
        @Override
        public void onTextChanged(CharSequence s, int i, int i1, int i2) {

            int number = Integer.parseInt(s.toString());

            if (number >=100){
                tilNmaReason.setVisibility(View.VISIBLE);
            }
            else{
                tilNmaAmount.setError(null);
            }

        }
        @Override
        public void afterTextChanged(Editable editable) {

        }
    });
}

Updated

I have this data

  String amt = edt_nma_amount.getText().toString();
  int numbers=Integer.valueOf(amt);

but it returns me an error AT int numbers=Integer.valueOf(amt); I think it is NumberFormatException

enter image description here

Advertisement

Answer

Please change the code inside onTextChanged call back

              if (!TextUtils.isEmpty(s.toString())) {
                     Long number =    Long.parseLong(s.toString());

                if (number >= 100) {
                    tilNmaReason.setVisibility(View.VISIBLE);
                } else {
                    tilNmaAmount.setError(null);
                }

            }else{
                tilNmaAmount.setError(null);
            }
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement