0

I have made an EditText where I type inside it some name.

I had like the app to perform search every time something changed in my EditText.

I used the following code:

txt_search.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) {
        query = txt_search.getText().toString();
        fetchBooks(query);
    }

    @Override
    public void afterTextChanged(Editable s) {
        query = txt_search.getText().toString();
        fetchBooks(query);
    }
} );

Where fetchBooks is the method that performs the search inside the API based on the query.

The problem im facing is that sometimes the search is stuck. If for example, I type pretty fast, it gives the results only for the first few letters and not for the whole query in the end.

Eventually, what I'm trying to get is that the app will constantly perform search based on the text inside the EditText.

Is there a way to obtain it without getting stuck results?

Thank you

Alireza Bideli
  • 834
  • 2
  • 9
  • 31
Ben
  • 1,737
  • 2
  • 30
  • 61

1 Answers1

0

First: Remove search operation code for AfterChangedListener because after text is entered in EditText completely your search operation execute on both onTextChanged listener and afterTextChanged Listener

Second Replace txt_search.getText().toString(); with 's.toString()'

Change your TextWatcher as below

txt_search.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) {
            query = s.toString();
            fetchBooks(query);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    } );

For more information I recommend you to see below links:

getText vs onTextChanged charSequence

android Edittext with textwatcher

Alireza Bideli
  • 834
  • 2
  • 9
  • 31