0

I have activity with listview and custom listadapter. EveryItem of List starting a AsyncTask request. Now when i click onback it finish the activity but asynctask isn't finishing. How to finish this all AsyncTask ?

public class MyListAdapter extends ArrayAdapter<String>
{

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
   ......
   if(!status.get(position).isFetch)
            {
                statusList.get(position).FetchingData=true;
                GetRequest request=new GetRequest();
                request.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, id);
            }
 .....
}

class GetRequest extends AsyncTask<String, String, String>
{......}

}

if i pressed backbutton before completing all item task then its finishing activity but not task. How to stop asynctask as activity finish..

1 Answers1

0

You should stop all the tasks manually. Activity lifecycle won't take care of your tasks automatically.

You should manage all the tasks in somewhere(I suggest Activity or Fragment, not in ListView). Gather all the tasks in list and stop'em on onDestroy(or onPause depending your situation).

public MyActivity extends Activity {
    private ArrayList<SomeTask> mTasks;

    private void startTasks() {
        SomeTask task = new SomeTask();
        task.execute();
        mTasks.add(task);
    }

    @Override void onDestroy() {
        for (SomeTask task : mTasks) {
            tasks.cancel(true);
        }
    }

private class SomeTask extends AsyncTask<Void, Void, Void> {

         private MyListItem mItem;
         private int mIndex;

         public SomeTask(MyListItem item, int index) {
             mItem = item;
             mIndex = index;
         }

         protected Long doInBackground(Void... urls) {
             // do whatever you want
             return null;
         }

         protected void onPostExecute(Void result) {
             // update your adapter here
         }
     }
}

Sadly, AsyncTask won't just stop even if you call task.cancel(true). You also have to check if the task is cancelled inside the AsyncTask. Below is a sample taken from AsyncTask reference page:

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
 protected Long doInBackground(URL... urls) {
     int count = urls.length;
     long totalSize = 0;
     for (int i = 0; i < count; i++) {
         totalSize += Downloader.downloadFile(urls[i]);
         publishProgress((int) ((i / (float) count) * 100));
         // Escape early if cancel() is called
         if (isCancelled()) break;
     }
     return totalSize;
 }

 protected void onProgressUpdate(Integer... progress) {
     setProgressPercent(progress[0]);
 }

 protected void onPostExecute(Long result) {
     showDialog("Downloaded " + result + " bytes");
 }

}

Checkout Cancelling a task section for more information.

Chris Jeong
  • 363
  • 3
  • 10
  • how to gather all task as all starts in arrayadapter and cancelling it from activity ? – Sagar Surani Mar 16 '16 at 12:42
  • issue solved but not completely .. starting 10-12 task parallely using thread pool executor in adapter class, storing it in arraylist and cancelling it in parent activity. here something went wrong, next http request blocks for some amount of time.. – Sagar Surani Mar 17 '16 at 07:45
  • I think you should post this question as a new question(since it's obviously different issue from this question), but I'll answer anyway. AsyncTask can run limited count of tasks concurrently and the count is different depending on Android OS version. Checkout http://stackoverflow.com/questions/9654148/android-asynctask-threads-limits. – Chris Jeong Mar 17 '16 at 07:52
  • And if this or any answer has solved your question please consider [accepting it](http://meta.stackexchange.com/q/5234/179419) by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this. – Chris Jeong Mar 17 '16 at 08:06