【问题标题】:Is it Possible to execute AsyncTask with ArrayList<ModelClass> as parameter in android?是否可以在 android 中使用 ArrayList<ModelClass> 作为参数执行 AsyncTask?
【发布时间】:2017-03-11 17:19:27
【问题描述】:

我正在尝试执行 AsyncTask 以从我的 Fragment 类中的服务器下载图像:

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 背景,或者是否有更好的方法将下载的图像与图像详细信息同步?

【问题讨论】:

  • 您可以将任何对象设置为 AsyncTask 的参数,因此 ArrayList 应该可以很好地传递给 doInBackground
  • 我正在关注本教程 theopentutorials.com/tutorials/android/dialog/… 并愿意使用 ArrayList 执行任务,而不是“task.execute(new String[] { URL, URL1, URL2 });”

标签: java android multithreading android-asynctask runnable


【解决方案1】:

正如谷歌在官方文档中所说,您可以将RowItem 或其他对象类型作为通用类型 提供给AsyncTask

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

您的 onDoingBackground 方法如下所示:

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 中类型参数的声明

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[]));

【讨论】:

  • 因为我在 Viewpager 中使用了我的 SubFragment,它在父 Fragment 中与 MainActivity 一起使用,我发现很难缓存图像,所以决定将图像和其他数据存储到 sqlite ...关于你在 doInbackground 中的答案()您正在循环字符串,它不是方法中的参数,并且在从 asyncTask.execute 执行任务时如何传递通用类型..
  • 我编辑了我的答案。您仍然可以为此使用库。您也可以将列表作为构造函数参数传递给 AsyncTask,但这并不安全。
  • 感谢@savepopulation 的回答,实际上我愿意将 Arraylist 与 modelclass 一起传递,并在 postexecute 上将 Output as ArrayList 作为 Model ......我做到了,感谢指导......跨度>
猜你喜欢
  • 2015-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-18
相关资源
最近更新 更多