Ago
Ago

Reputation: 765

How to implement AsyncTask inside a while loop

I'm new in Android and I have a problem with threading. Here is what I want:

ArrayList<MODEL_Records> records = SQLITE.getInstance().getRecords();
int length = records.size();
for(int i =0; i < length; i++){
    (new AsynchTask().execute(records.get(i)));
    // wait for the asynchTask to finish executing before iterating
}

Am I asking the right question? can someone point me to the right track?

Upvotes: 0

Views: 535

Answers (1)

Russell Elfenbein
Russell Elfenbein

Reputation: 551

You should not do this in the UI thread as your while loop will block the code and force a ANR (App Not Responding?) error.

Further to the point, if you want to run your task in a background thread (AsyncTask) you shouldnt block the UI thread to do it, this is counterproductive.

Also, I cant tell what your getRecords() method does, but it appears that you are no longer trying to access the DB, but are accessing an array, which should be quite quick.

If you want to improve this, rather than putting your asynctask in the while loop, put the while loop in the AsyncTask#doInBackground(), then call up whatever you require in your AsyncTask#onPostExecute(). This would push your slow processing into a background thread.

Upvotes: 1

Related Questions