Filter ListView in real time

android, android-asynctask, android-listview

Solution

Hmmm...Not totally sure why your using `AsyncTask` for search in real-time. Here's how I would(and have successfully) do it.

Add a `TextChangeListener` to your `Edittext`:

editText.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            searchResults = myDbHelper.searchAll(s.toString());
            searchAdapter.notifyDataSetChanged();
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });

I am searching through a sqlite database everytime a user presses a key. My `searchResults` is used to populate the `ListView`, and so after I set the get the search results, tell the list adapter that the data set changed.

Hope this helps.

Problem

I want to filter a `ListView` in real time. I have an `EditText` in the `ActionBar`, and each time the user writes a character I want to update the cursor of the `ListView` filtering the information. I have done an `AsyncTask` to perform the query but I have two questions: 1º) If the user types three characters I'm creating three `AsyncTasks` (one to search the first character, one to search the two first characters, and finally one to search the three characters). Is there a simple way to say to the `AsyncTask` to replace the previous task with the new one? 2º) How can I put a small delay to start the `AsyncTask`? So if the user types three characters without stopping, I will not create the `AsyncTask` until the end. Thanks!

Original source