2012-02-15 137 views
0

我有两个功能,在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"; 
} 

我不知道该怎么回报。

回答

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) { 
    ... 
} 
0

doInBackground取决于你需要在执行后有什么方法的返回类型:

void postExecute(Object result); // AsyncTask method 

参数“结果”是doInBackground的返回值。所以如果你不需要任何东西你会返回NULL。

+0

导致应用程序崩溃。 – Nick 2012-02-15 16:06:04

+0

你确定崩溃在这里吗?如果不是,你使用postExecute吗? – damson 2012-02-15 18:34:17