Home > Software design >  Android : Convert CharSequence to Int in Java
Android : Convert CharSequence to Int in Java

Time:10-03

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

CodePudding user response:

You have to check if onTextChanged gives you an empty string or not before calling parseInt.

    @Override
    public void onTextChanged(CharSequence s, int i, int i1, int i2) {
        if (s.toString().isEmpty()) { // <----
            tilNmaAmount.setError(null);
        } else { // <----
            int number = Integer.parseInt(s.toString());

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

CodePudding user response:

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);
            }
  • Related