Throttle onQueryTextChange in SearchView

aherrick picture aherrick · Jan 22, 2016 · Viewed 7.9k times · Source

What's the best way to "throttle" onQueryTextChange so that my performSearch() method is called only once every second instead of every time the user types?

public boolean onQueryTextChange(final String newText) {
    if (newText.length() > 3) {
        // throttle to call performSearch once every second
        performSearch(nextText);
    }
    return false;
}

Answer

Amit picture Amit · May 22, 2016

Building on aherrick's code, I have a better solution. Instead of using a boolean 'canRun', declare a runnable variable and clear the callback queue on the handler each time the query text is changed. This is the code I ended up using:

@Override
public boolean onQueryTextChange(final String newText) {
    searchText = newText;

    // Remove all previous callbacks.
    handler.removeCallbacks(runnable);

    runnable = new Runnable() {
        @Override
        public void run() {
            // Your code here.
        }
    };
    handler.postDelayed(runnable, 500);

    return false;
}