Search code examples
androidsearchview

how to get the time between User input text twice?


I use SearchView in my android app, I monitor the onQueryTextChange event, what i don't want to filter the result when every time user input text, I want to filter the result only when User want to filter, I solution is to get the time every time user input text, when the time is bigger than 1s, I will query the result for the search, How can I do that?


Solution

  • You can create a timer that resets every time the input changes.

    Timer mTimer;
    
    ...
    
    public boolean onQueryTextChange (String newText) {
        if (mTimer != null) {
            mTimer.cancel();
        }
        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                search(newText);
            }
        }, 1000);
    
        ...
    }
    

    You could also use onQueryTextSubmit to search only when the user wants to.