我有一个问题,我试图从web api加载图像。我可以这样做,但是当我试图把它们放入对象的属性中时它就会崩溃。我看了所有的例子如何异步加载图像我能找到,但每个人我找到什么分配给一个imageview,而不是对象。
下面是调用代码 的示例 Movie Example = new Movie();
DownloadImageTask task = new DownloadImageTask();
String path = "http://d3gtl9l2a4fn1j.cloudfront.net/t/p/original" + example.getProfile_path();
example.setProfile(task.execute(path).get());
这是我用来获取图像
的方法private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
private ImageView bmImage;
public DownloadImageTask() {
this.bmImage = new ImageView(getActivity());
}
protected void onPreExecute() {
}
protected Bitmap doInBackground(String... urls) {
try{
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap result = BitmapFactory.decodeStream(input);
return result;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
protected void onPostExecute(Bitmap result) {
//set image of your imageview
try {
bmImage.setImageBitmap(result);
//close
} catch (Exception ex) {
Log.e("ERROR", "can't assign image to view");
}
}
}
我想要类似的东西,但不是分配给imageview它会返回图像给调用它的方法。
实际上,将图像返回给调用它的方法没有多大意义,因为该方法必须挂起自己并等待图像加载,这违背了让图像并行加载的目的。你到底想要完成什么?
如果你真的想这样做,我想它可以通过修改你的AsyncTask来完成,像这样:
private class DownloadImageTask extends AsyncTask<String, Void, Void> {
private ImageView bmImage;
private boolean finished = false;
private Bitmap resultingBitmap = null;
protected Void doInBackground(String... urls) {
try{
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
resultingBitmap = BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
}
finished = true;
}
public boolean isFinished() {
return finished;
}
public Bitmap getResultingBitmap() {
return resultingBitmap;
}
}
呼叫者代码:
DownloadImageTask task = new DownloadImageTask();
String path = "http://d3gtl9l2a4fn1j.cloudfront.net/t/p/original" + example.getProfile_path();
while (!task.isFinished()) { } // this defeats the purpose of parallel execution
example.setProfile(task.execute(path).getResultingBitmap());
你可以按照@Brandon的回答来完成:
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
Example example;
public DownloadImageTask(Example example) {
this.example = example;
}
(...)
protected void onPostExecute(Bitmap result) {
example.setProfile(result);
}
}