Shakti
Shakti

Reputation: 1581

How to create Array of AsyncTask Objects?

I am creating multiple AsyncTask instances. I would like to create an array of AsyncTask to use these references to cancel the task later on but i am not able to figure out how to create an Array.

private AsyncTask<Integer, Void, Bitmap> mLoadTask;

private void loadTask(final Integer sInt){
mLoadTask = new AsyncTask<Integer, Void, Bitmap>() {                

    @Override 
    protected void onPostExecute(Bitmap result) {

    ...             

    }

    @Override
    protected Bitmap doInBackground(Integer... params) {        

    ...

    }

};

mLoadTask.execute(sInt);
}

I would like for mLoadTask to be called as an array element i.e one for each new task. Something like this

mLoadTask[sInt].execute(sInt)

Please suggest how to modify my code to achieve something like this or if there is another approach to this which would better suit.

Upvotes: 0

Views: 847

Answers (1)

zgc7009
zgc7009

Reputation: 3389

Do just that, create an Array of tasks. Something that might help you in understanding what you are doing is to create a class that extends AsyncTask, which you could create an explicit Array of. Do something like this.

private MyAsyncTask[] mLoadTasks;

public void onCreate...{
    super.onCreate...;

    ...

    mLoadTasks = new MyAsyncTask[size_of_array];
}

private void loadTask(int sInt){
    mLoadTasks[sInt].execute(sInt);
}

public class MyAsyncTask extends AsyncTask<Integer, Void, Bitmap>{                

    @Override
    protected Bitmap doInBackground(Integer... params) {        
        ...
    }

    @Override 
    protected void onPostExecute(Bitmap result) {
        ...             
    }

}

If you don't know the size of your array at compile time you would need to create a List (since Lists can dynamically shrink/expand as needed).

This may not be the only way to do things, but it is readable and easy enough :)

Upvotes: 4

Related Questions