Android asyncTask无法将ArrayList <>作为param传递

问题描述 投票:0回答:3

我有这个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() {

    }
}

但是在我的foreach循环中,我得到错误,说需要ArrayList找到String。是否有可能asynctask将我的arraylist转换为String?

android arraylist android-asynctask
3个回答
2
投票

你不需要AsyncTask<ArrayList<String>,,除非你想传递ArrayList数组。 ...运算符称为varargs,它可以像数组一样访问。例如。如果你打电话

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

然后,在

protected File doInBackground(String... files) {

files[0]包含afiles[1]包含b。如果您仍想传递ArrayList,则必须更改代码,如下所示:

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

1
投票

尝试通过这种方式更改protected File doInBackground(ArrayList<String>... files) {

protected File doInBackground(ArrayList<String>... files) {
        ArrayList<String> passedFiles = files[0]; //get passed arraylist

        for(String file : passedFiles){
        //DO SMTH
        }
        return null;
    }

0
投票

你必须做这样的事情

    Items[] items = new Items[SIZE]; 
    items[0]=ITEM1;
    items[1]=ITEM2;
    items[2]=ITEM3;
    .
    .
    .

    new InsertItemsAsync().execute(items);   

private static class InsertItemsAsync extends AsyncTask<Items,Void,Void>{
        @Override
        protected Void doInBackground(Items... items) {
          // perform your operations here
            return null;
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.