2017-03-11 24 views
0

我想exectue的AsyncTask下载从服务器镜像在我的片段类为:是否可以使用ArrayList <ModelClass>作为android中的参数执行AsyncTask?

GetImageTask task = new GetImageTask (getActivity()); 
task.execute(new String[]{ imageUrlList.get(0), imageUrlList.get(1), imageUrlList.get(2) }); 

在doinBackground:通过使用此代码我能够从服务器下载图像

protected List<RowItem> doInBackground(String... urls) { 
    rowItems = new ArrayList<RowItem>(); 
    Bitmap map = null; 
    for (String url : urls) { 
    map = downloadImage(url); 
    rowItems.add(new RowItem(map)); 
    } 
    return rowItems; 
} 

却苦于不与其他数据信息同步显示在Listview中。

是否有可能使用ArrayList执行AsyncTask背景还是有更好的方法来同步下载的图像和图像细节信息吗?

+2

您可以设置任何对象作为一个的AsyncTask参数,因此ArrayList中应该只是罚款传递给doInBackground –

+0

我下面这个教程 HTTP ://theopentutorials.com/tutorials/android/dialog/android-download-multiple-files-showing-progress-bar/并且愿意使用ArrayList 而不是“task.execute(new String [] {URL,URL1 ,URL2});“ –

回答

0

正如谷歌在官方文档中所说的,您可以给RowItem或其他对象类型为泛型类型AsyncTask

public class GetImageTask extends AsyncTask<RowItem, String, List<RowItem>> 

你onDoingBackground method'll是象下面这样:

protected List<RowItem> doInBackground(RowItem... rowItems) { 
    rowItems = new ArrayList<RowItem>(); 
    Bitmap map = null; 
    for (String url : urls) { 
    map = downloadImage(url); 
    rowItems.add(new RowItem(map)); 
    } 
    return rowItems; 
} 

我这里还有中的AsyncTask类型则params的声明

X – The type of the input variables value you want to set to the background process. This can be an array of objects. 

Y – The type of the objects you are going to enter in the onProgressUpdate method. 

Z – The type of the result from the operations you have done in the background process. 

您可以找到有关从这里异步任务的详细信息: https://developer.android.com/reference/android/os/AsyncTask.html

注意:我建议你使用图像库加载操作。因为处理图像下载操作要复杂得多。 (网络,缓存,内存使用等)

这个工作有很多有用的库。您可以使用奥托的毕加索 http://square.github.io/picasso/

或者其他库:

通用图像装载机: https://github.com/nostra13/Android-Universal-Image-Loader

滑翔: https://github.com/bumptech/glide

壁画: https://github.com/facebook/fresco

好运。

EDIT2:您可以执行比如:

myTaskInstance.execute(rowItemsList.toArray(new RowItem[])); 
+0

因为我在ViewPager中使用SubFragment,它在MainActivity中在Parent Fragment中声明,所以我发现很难缓存图像,因此决定将图像和其他数据存储到sqlite中。关于您在doInbackground()中的回答您正在循环字符串,它不是在方法中的参数,而是从asyncTask.execute执行任务时如何传递泛型类型.. –

+0

我编辑了我的答案。你仍然可以使用这个库。您也可以将您的列表作为constrcutor参数传递给AsyncTask,但这并不安全。 – savepopulation

+0

感谢@savepopulation实际上我愿意将模型类传递给Arraylist,并获得Output作为ArrayList作为model在postexecute .....我做了它,谢谢指导.... –

相关问题