horin horin - 1 month ago 12
Android Question

Android asyncTask cant pass ArrayList<> as param

I have this asyncTask:

public class CreateZipFile extends AsyncTask<ArrayList<String>, Integer, File> {

Context context;

public CreateZipFile(Context context){
this.context = context;
}

protected File doInBackground(ArrayList<String>... files) {
for(String file : files){
//DO SMTH
}
return null;
}

public void onProgressUpdate(Integer... progress) {

}

public void onPostExecute() {

}
}


however in my foreach loop I get error saying required ArrayList found String. Is it possible that asynctask converts my arraylist to String?

Answer

you don't need AsyncTask<ArrayList<String>, unless you want to pass an array of ArrayList. The ... operator, is called varargs, and it can be accessed like an array. E.g. if you call

 new CreateZipFile().execute("a", "b");

then, in

protected File doInBackground(String... files) {

files[0] contains a and files[1] contains b. If you still want to pass the ArrayList, then you have to change your code like follows:

 for (ArrayList<String> l : files) {
       for(String file : l){
           //DO SMTH
       }
   }