[英]What to return for an Async Task
I have two functions that access the internet on the APP start. 我有两个可以在APP启动时访问Internet的功能。 I've tried to use this post as a reference in order to have the popup dialog while my content loads.
我尝试将这篇文章用作参考,以便在加载内容时出现弹出对话框。
The two functions I would use are: 我将使用的两个功能是:
getImage(); //Gets an image from the internet for an imageview
getJson(); //Where the app goes an parses a JSON object for a lazy load listview.
The problem I'm encountering with the post I referenced above is that I try to make the task return null but it causes the app to crash when I do this. 我在上面引用的帖子遇到的问题是,我尝试使任务返回null,但这样做会使应用程序崩溃。 So I have this:
所以我有这个:
private class DownloadTask extends AsyncTask<String, Void, Object> {
protected Object doInBackground(String... args) {
Log.i("MyApp", "Background thread starting");
try {
ImageView i = (ImageView) findViewById(R.id.currdoodlepic);
Bitmap bitmap = BitmapFactory
.decodeStream((InputStream) new URL(imageURL)
.getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
getJson("all");
return "replace this with your data object";
}
I'm not sure what to return. 我不确定该返回什么。
The type return of the method doInBackground depend of what you need at the post execution : 方法doInBackground的类型返回取决于执行后所需的条件:
void postExecute(Object result); // AsyncTask method
Parameter "result" is the return value of doInBackground. 参数“结果”是doInBackground的返回值。 So if you need nothing you return NULL.
因此,如果您什么都不需要,则返回NULL。
I found the exact answer here . 我在这里找到了确切的答案。 Here is the code:
这是代码:
ImageView mChart = (ImageView) findViewById(R.id.imageview);
String URL = "http://www...anything ...";
mChart.setTag(URL);
new DownloadImageTask.execute(mChart);
The Task class: Task类:
public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> {
ImageView imageView = null;
@Override
protected Bitmap doInBackground(ImageView... imageViews) {
this.imageView = imageViews[0];
return download_Image((String)imageView.getTag());
}
@Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
private Bitmap download_Image(String url) {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.