Delay call to onQueryTextChange() in SearchView.OnQueryTextListener with SearchView

Shubham A. picture Shubham A. · May 5, 2015 · Viewed 8k times · Source

Using a SearchView in my application.

Is there anyway in which I can make the call to onQueryTextChange() method delayed. Like, when user type a sequence of characters, he must wait before this method gets called.

This wait should not depend on number of characters typed yet but a small pause is required before method being hit.

I want to pause because, as the user types into the search view, a request with the string will be made to server to request the matched data, and then I will populate my ListView according to suggestions.

Activity information (if required) :
Implements SearchView.OnQueryTextListener.

    MenuItem searchItem = menu.findItem(R.id.action_search);
    SearchView searchView = (SearchView)MenuItemCompat.getActionView(searchItem);
    searchView.setOnQueryTextListener(this);

Answer

killianke picture killianke · Oct 30, 2015

To delay the call to your server, use the following code in your onQueryTextChange method, the variables mQueryString and mHandler must be class variables. also check mHandler!=null

@Override
public boolean onQueryTextChange(String searchTerm) {
    mQueryString = searchTerm;
    mHandler.removeCallbacksAndMessages(null);

    mHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
           //Put your call to the server here (with mQueryString)
        }
    }, 300);
    return true;
}