Issue
I am calling an AsyncTask in the onQueryTextChange method of a SearchView and displaying the results in a list. The searching works, but occasionally tends to hang for a second if the user types quickly in the searchview. I want to further optimize this approach. Since its an autocomplete Search, as the user starting typing, several AsyncTasks gets queued for execution. But I am only interested in the very last searchrequest.
Currently, I am doing something like this
if (myAsyncTask != null)
myAsyncTask.cancel(true);
myAsyncTask = new MyAsyncTask(context,URL);
Is there a better way to do this? I would like to do something like this, if possible
myAsyncTask.executeOnExecutor(new OptimizedExectionerService);
The OptimizedExectionerService class should cancel all pending and runnning tasks in the pool and ONLY process the last request that was made.
Solution
Use a handler with a reasonable delay (to handle typing into an edittext).
private static final int SEARCH_DELAY = 500;
private Handler mHandler = new Handler();
private SearchRunnable executeSearch = new SearchRunnable();
private queueSearch(String term) {
// Remove any previous searches
mHandler.removeCallbacks(executeSearch);
// Set the search term for the runnable
executeSearch.setSearchTerm(term);
// Schedule the search in half a second
mHandler.postDelayed(executeSearch, SEARCH_DELAY);
}
private class SearchRunnable implements Runnable {
String searchTerm = null;
public void setSearchTerm(String term) {
searchTerm = term;
}
@Override
public void run() {
//Execute Search here
new MyAsyncTask(context, searchTerm);
}
};
Answered By - jt-gilkeson
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.