Trying to use AsyncTask do download some image files

别等时光非礼了梦想. 提交于 2019-12-20 06:38:56

问题


I have list of files stored inside arraylist that I need to download in background thread. My initial thought is that AsyncTask should be up for that task. But, I have a problem, I don't know how to supply my list to doInBackground method.

My arraylist is defined as

private ArrayList<String> FilesToDownload = new ArrayList<String>();

My DownloadFiles subclass (the way it is written now) should be called with: new DownloadFiles().execute(url1, url2, url3, etc.);

This is not suitable for me since I never know how many urls I will have. It is pretty much changing from case to case. So, I would like somehow to pass my arraylist to doInBackground method.

I tried to convert to array with toArray():

new DownloadFiles().execute(FilesToDownload.toArray());

But, eclipse tells me that execute is not applicable for argument Object[]. Suggestion was to cast to URL[], but when I tried that I got illegal casting error and app crashed.

It seems that doInBackground has to be implemented with parameters in varargs type (URL... urls).

Any ideas how to solve my problem? Thanks.

class DownloadFiles extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;        
         for (int i = 0; i < count; i++) {
             Log.d("Evento", "&&&& downloading: " + FilesToDownload.get(i).toString());
//             totalSize += Downloader.downloadFile(urls[i]);
//             publishProgress((int) ((i / (float) count) * 100));
         }
         return totalSize;
     }
     protected void onProgressUpdate(Integer... progress) {
        //setProgressPercent(progress[0]);
     }
     protected void onPostExecute(Long result) {
       //showDialog("Downloaded " + result + " bytes");
     }
}

回答1:


Your AsyncTask is declared with a param type of URL, but you're trying to pass String (or ArrayList) objects. Either prepare an Array of URL objects in the calling program or modify DownloadFiles to accept String instead of URL parameters and convert each String to a URL in the execute() method.

Better yet, since you are accessing FilesToDownload from within execute(), you don't need to pass anything to execute() and you could declare the first generic parameter of DownloadFiles as Void.



来源:https://stackoverflow.com/questions/5054364/trying-to-use-asynctask-do-download-some-image-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!