addTextChangedListener onTextChanged count Not working On android version 10

666 Views Asked by At

I use addTextChangedListener to search item from server with retrofit. but only android version 10 onTextChanged count not working...?

Here is my code

searchEdit.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) {

            if (count>1) {
                String name = searchEdit.getText().toString().trim();

                if (!name.isEmpty()) {
                    searchItemByName(name);
                }
            }
        }
        @Override
        public void afterTextChanged(Editable s) {
            
        }
    });
1

There are 1 best solutions below

0
mhdwajeeh.95 On

I'll go with the assumption that you're using count parameter in onTextChanged callback as the number of characters inside your searchEdit Edittext.

Solution: You need to use s.length() function instead of the parameter count, like this:

searchEdit.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) {

                if (s.length()>1) {
                    String name = searchEdit.getText().toString().trim();

                    if (!name.isEmpty()) {
                        searchItemByName(name);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

Explanation:

If you have a look at the documentation of android.text.TextWatcher::onTextChanged function below:

/**
     * This method is called to notify you that, within <code>s</code>,
     * the <code>count</code> characters beginning at <code>start</code>
     * have just replaced old text that had length <code>before</code>.
     * It is an error to attempt to make changes to <code>s</code> from
     * this callback.
     */
    public void onTextChanged(CharSequence s, int start, int before, int count);

it says that count parameter refers to the number of characters changed in s, and thus, if you're typing into the edittext your onTextChanged function will be called with the parameter count is 1.

Alternatively: you can use afterTextChanged callback with s.length().