I am currently making a validation, where I have an edittext with inputtype number, used to show quantity of items bought in user's cart. I want to make sure that when the edittext's value is edited, if the value is "", "0", or "00", etc, as long as it is < 1, then the value will be set into "1".
I have tired the below's code:
txtJumlah.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
int jumlah = Integer.parseInt(txtJumlah.getText().toString());
if(txtJumlah.getText().toString().equals("") || jumlah <= 1) {
txtJumlah.setText("1");
}
calculate();
}
});
But it returns a java.lang.StackOverflowError: stack size 8MB
Can anyone help me? thanks
When you set the text to "1" it will call afterTextChanged again and again causing an infinite loop. Try putting jumlah < 1 in your if statement instead.
replace this:
if(txtJumlah.getText().toString().equals("") || jumlah <= 1) {
txtJumlah.setText("1");
}
by:
if(txtJumlah.getText().toString().equals("") || jumlah < 1) {
txtJumlah.setText("1");
}
Above solution must solve the problem.
One suggestion to optimize your code:
int jumlah = Integer.parseInt(txtJumlah.getText().toString());
This can cause ParseException
(if txtJumlah.getText().toString()
is string rather than numbers)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.