Please read my question description. I am not getting the right way how to ask this question . But the description will explain you my problem.
Ok so , I am having an EditText
, I want that when user enters a number greater than 500 in the EditText
, a drawable
(tick sign) should be visible (indicating that entered number is correct).
And after entering the number suppose User backspace and remove the number entered (makes the number less than 500
), the drawable should be invisible .
I have done this using Textwatcher
but the problem is that when user start to remove the entered number , i get error and the app crashes. Example - If i entered 500 ... everything is ok and the drawable is also visible . Now I remove 1 zero of 500 , now editext has value 50 and drawable is also invisible. Now i remove another 0 , edittext has value 5 now . Till here everything is OK . Now when i remove the 5
, app crashes and gives error. Please someone tell me what i am doing wrong here?
Screenshot of the activity...edittext scrrenshot
This is what i am doing ..
ets2.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if((Long.parseLong(ets2.getText().toString().trim())<500) || (ets2.length()==0) /*||(TextUtils.isEmpty(ets2.getText().toString()))*/){
step2tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
invalidtv.setVisibility(View.VISIBLE);
ets2.setError("Please enter amount \n greator than 500");
} else{
step2tv.setCompoundDrawablesWithIntrinsicBounds(0, 0,R.drawable.ic_checkgreen, 0);
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
CodePudding user response:
First, whenever you have a crash, post the stack trace. It tells you why it crashed.
Here, it's easy to guess. When the string is empty, parseLong will throw an exception because "" can't be parsed to a long. The way to fix that is to catch NumberFormatException and treat that as a failure.