Search code examples
androidsearchview

SearchView onQueryTextChange ignore previous characters and only use last typed character


Is there a way to ignore all the previous characters entered, that get passed to onQueryTextChange until the last character is entered?

For example, if user types S Y M B O L, it performs a query every time every time the character is entered, so it performs 6 queries. I want to cancel the previous 5 queries, and only run the last one.

"select * from table where name  LIKE  :searchText || '%' order by name  limit 500"

My table has over 700,000 items in it, so the screen takes about a few seconds to be updated, and I would like it to be updated immediately. If the user types slow, it's ok, but if they type fast, the screen update is very slow.

I am using RecyclerView and query returns LiveData.

I do have an index on this particular column, so that's not the problem.

Is there a solution for this?


Solution

  • You can use onQueryTextSubmit() callback for passing the final typed string

    searchView.setOnQueryTextListener(
                new SearchView.OnQueryTextListener() {
    
                    @Override
                    public boolean onQueryTextSubmit(String query) {
                        Intent intent = new Intent(context, SearchResultActivity.class);
                        intent.putExtra(QUERY, query);// Perform search task with query string 
                        context.startActivity(intent);
                        return false;
                    }
    
                    @Override
                    public boolean onQueryTextChange(String newText) {
                        return false;// triggered every time you type a character 
                    }
                }
        );
    

    Hope it helps