当尝试使用Asynctask从url检索图像时,我得到此错误。这是我的asynctask:
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap result = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
result = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return result;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
if (result != null && !result.isRecycled()) {
result.recycle();
result = null;
}
}
}
如果我删除result.recycle(),错误将是OutofMemoryError。我从不同的url检索多个图像。我该怎么做呢?我调用asynctask:
new DownloadImageTask(imageview[i]).execute(paths.get(i));
非常感谢,
你不能在这里回收,因为你仍然需要位图。问题是,这些位图使用的内存总量大于可用内存总量(当添加到应用程序已经使用的内存中时)。正因为如此,一个人给出的使用库的建议是没有用的——它不会增加内存。这里有一些你可以做的事情:
1)减少你的应用程序使用的内存。可能是可能的,也可能不是,看看堆分析器,看看你是否有内存泄漏。
2)不要一次下载所有图片。
3)而不是将它们下载到内存中,而是将其写入文件并仅在实际需要时打开每个图像。这可以与LRUCache结合使用,以确保您永远不会使用超过固定数量的内存。
使用picasa库
ImageView product_image = (ImageView) itemview
.findViewById(R.id.product_image);
Picasso.with(context)
.load(product_order_details.get(position).product_image)
.placeholder(R.drawable.defalutimage).fit().into(product_image);