Delay call to onQueryTextChange() in SearchView.OnQueryTextListener with SearchView
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;
}
This should help you, your class need to implement "SearchView.OnQueryTextListener" and "cntr" must be declarated in your class
This is already twinked for a regular user typing, if you want to wait more, just raise the "waitingTime".
The request should be inside the "onFinish"
private int waitingTime = 200;
private CountDownTimer cntr;
@Override
public boolean onQueryTextChange(String newText) {
if(cntr != null){
cntr.cancel();
}
cntr = new CountDownTimer(waitingTime, 500) {
public void onTick(long millisUntilFinished) {
Log.d("TIME","seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
Log.d("FINISHED","DONE");
}
};
cntr.start();
return false;
}
You can use Kotlin coroutines like this. Declare the countdown job
private lateinit var textChangeCountDownJob: Job
And then onQueryTextChange:
override fun onQueryTextChange(newText: String): Boolean {
if(::textChangeCountDownJob.isInitialized)
textChangeCountDownJob.cancel()
textChangeCountDownJob = launch(UI) {
delay(800)
}
return false
}