0

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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)

1 Comment

txtJumlah.getText() will never return null. It will always return an empty String. The only thing that could cause a NullPointerException is if the TextView was null. Even if you try to setText(null) it will convert it to an empty String.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.