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