我一直在摸不着头脑 - 任何见解都会非常有益。
这是我第一次玩AsyncTask而且我对我在这里做错了有点困惑--Eclipse正在说:“这个方法必须返回类型对象的结果”但是;我看不出它是怎么回事 - 除非我在这里完全遗漏了什么。
我正在尝试下载一个图像并将其显示在imageView1上(另外,如果你能节省一些时间并告诉我,我是否正确运行了我的postExecute代码,那将会很棒:)) / p>
private class DownloadImageTask extends AsyncTask<String, Void, Object> {
protected Object doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
Object content = url.getContent();
return content;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
protected void onPostExecute(Object result) {
InputStream is = (InputStream) result;
Drawable d = Drawable.createFromStream(is, "src");
ImageView imgView = (ImageView)findViewById(R.id.imageView1);
imgView.setImageDrawable(d);
}
}
答案 0 :(得分:2)
当您捕获异常时,您没有返回任何内容,因为它显示消息“此方法必须返回类型对象的结果”。请在捕获异常时返回任何对象或null 。
此外,如果你得到的是drawable而不是你的postexecute方法是正确的。
您的代码应如下所示:
private class DownloadImageTask extends AsyncTask<String, Void, Object> {
protected Object doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
Object content = url.getContent();
return content;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;//added
} catch (IOException e) {
e.printStackTrace();
return null;//added
}
}
protected void onPostExecute(Object result) {
InputStream is = (InputStream) result;
Drawable d = Drawable.createFromStream(is, "src");
ImageView imgView = (ImageView)findViewById(R.id.imageViewMaricoLogo);
imgView.setImageDrawable(d);
}
}
答案 1 :(得分:1)
我想你只想将String(URL)传递给AsyncTask,所以你的代码应该很简单,
private class DownloadImageTask extends AsyncTask<String, Void, Void>
{
@Override
protected Void doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
Object content = url.getContent();
return content;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
InputStream is = (InputStream) result;
Drawable d = Drawable.createFromStream(is, "src");
ImageView imgView = (ImageView)findViewById(R.id.imageView1);
imgView.setImageDrawable(d);
}
}
答案 2 :(得分:1)
你的doInBackground()没有返回任何内容,这就是你收到错误的原因。这发生在我之前,设置它返回一个你将在onPostExecute或null中使用的对象,它应该工作。祝你好运
答案 3 :(得分:0)
你的代码应该是这样的..
private class DownloadImageTask extends AsyncTask<String, Void, String> {//Notice i changed the Void, and String around in the parameters
protected Object doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
Object content = url.getContent();
return content;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
protected void onPostExecute(String result) {
InputStream is = (InputStream) result;
Drawable d = Drawable.createFromStream(is, "src");
ImageView imgView = (ImageView)findViewById(R.id.imageView1);
imgView.setImageDrawable(d);
}
}
编辑:
我将Object更改为String。这是你想要回归的对象吗?