要为异步任务返回什么

时间:2012-02-15 01:43:37

标签: android android-asynctask

我有两个在APP启动时访问互联网的功能。我尝试使用this帖子作为参考,以便在我的内容加载时使用弹出对话框。

我将使用的两个函数是:

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.

我在上面提到的帖子遇到的问题是我尝试让任务返回null但是当我这样做时它会导致应用程序崩溃。所以我有这个:

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";
}  

我不知道该返回什么。

2 个答案:

答案 0 :(得分:0)

方法doInBackground的类型返回取决于执行后需要的内容:

void postExecute(Object result); // AsyncTask method

参数“result”是doInBackground的返回值。因此,如果您不需要任何内容​​,则返回NULL。

答案 1 :(得分:0)

我找到了确切答案here。这是代码:

ImageView mChart = (ImageView) findViewById(R.id.imageview);
String URL = "http://www...anything ...";

mChart.setTag(URL);
new DownloadImageTask.execute(mChart);

任务类:

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) {
   ...
}
相关问题