Rajiv yadav
Rajiv yadav

Reputation: 823

Best practice to use AsyncTask in autocomplete?

I am using Async task to populate auto-complete suggestions from server.

Problem: when user types and removes the text in edittext so many times. lets say he typed: cofee > cof > coffee >coffee late .... etc for so many times. for each text changed after 3 keyword(threshold) i am initializing an asynctask and ask for result. so in current scenario i have so many threads running in background. so some of my latest async threads are waiting for there chance. Whole this make my app very slow.

What can I do to tackle this problem?

Upvotes: 2

Views: 1131

Answers (3)

Mohammed A. Najjar
Mohammed A. Najjar

Reputation: 23

It worked for me by cancelling the task each time you change the text (if it is still running).

You need to define your request once outside the listener(private for the class), and then start your listener function by (if your request is not finished, then cancel it).

define your request out side the function

private YourSearchTaskClass YourTaskReq = new YourSearchTaskClass();

then start your addTextChangeListener/afterTextChanged by this

if (YourTaskReq.getStatus()!= AsyncTask.Status.FINISHED)
   YourTaskAvReq.cancel(false);

YourTaskReq= new YourSearchTaskClass(keyword);

Upvotes: 0

Josef Borkovec
Josef Borkovec

Reputation: 1079

You should cancel the current task before issuing a new one. Use AsyncTask#cancel(true) for that and make sure that the execution of the task can be quickly stopped. This means correct handling of interruption and frequent checking whether the task was cancelled in the body of AsyncTask#doInBackground.

And you cannot execute again the AsyncTask you have cancelled. You have to create a new one. (Trying to execute it again leads to IllegalStateExceptions)

Upvotes: 0

Prashant Thakkar
Prashant Thakkar

Reputation: 1403

If it is possible to load entire data from server at beginning...then you can avoid calling asynctask repeatedly and fetching the data from server. This will improve performance of you app. If data displayed in Listview is String, following link show how to filter it:

http://www.androidhive.info/2012/09/android-adding-search-functionality-to-listview/

And if custom object is used in ListView adapter, try:

Filtering ListView with custom (object) adapter

Hopefully this helps.

Upvotes: 1

Related Questions