我在尝试从 Web api 加载图像时遇到问题。我可以做到,但是当我尝试将它们放入对象的属性中时,它只会崩溃。我已经查看了所有关于如何异步加载我能找到的图像的示例,但是每个人我都找到了将其分配给图像视图而不是对象的内容。以下是我的部分来源。
这是调用代码的示例
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,而是将图像返回给调用它的方法。