在我的应用程序中,我正在从网络下载图像。为此,我第一次从网络下载图像,这些图像存储在 SD 卡中。下次,我会检查这些图像是否在 SD 卡中。如果是,则从 SD 卡获取,否则我将从网络下载。这些图像像列表一样显示。我反复(意味着连续向上/向下移动)滚动列表,然后我的应用程序崩溃了,并且出现内存不足异常。怎么处理呢。有谁能够帮助我。
堆栈跟踪:
09-12 13:40:42.640: ERROR/AndroidRuntime(3426): java.lang.OutOfMemoryError: bitmap size exceeds VM budget(Heap Size=7879KB, Allocated=3362KB, Bitmap Size=11402KB)
09-12 13:40:42.640: ERROR/AndroidRuntime(3426): at android.graphics.BitmapFactory.nativeDecodeFile(Native Method)
09-12 13:40:42.640: ERROR/AndroidRuntime(3426): at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:355)
09-12 13:40:42.640: ERROR/AndroidRuntime(3426): at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:433)
09-12 13:40:42.640: ERROR/AndroidRuntime(3426): at com.ibkr.elgifto.GiftCategories$itemlistadapter$4.getDrawableFromUrl(GiftCategories.java:830)
09-12 13:40:42.640: ERROR/AndroidRuntime(3426): at com.ibkr.elgifto.GiftCategories$itemlistadapter$4.run(GiftCategories.java:739)
09-12 13:53:32.450: INFO/WSP(332): [Receiver] next auto-sync alarm event is 180 mins later, at time: Mon Sep 12 16:53:32 GMT+05:30 2011
code
private Drawable getDrawableFromUrl(String imageUrl) {
// TODO Auto-generated method stub
String filename = imageUrl;
filename = filename.replace("/", "+");
filename = filename.replace(":", "+");
filename = filename.replace("~", "s");
File elgiftoimagesref = new File("/sdcard/Elgiftoimages/");
elgiftoimagesref.mkdir();
final File file = new File(elgiftoimagesref, filename);
BitmapDrawable SDdrawable = null;
boolean exists = file.exists();
if (!exists) {
try {
URL myFileUrl = new URL(imageUrl);
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
final Bitmap result = BitmapFactory.decodeStream(is);
is.close();
new Thread() {
public void run() {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
if (result != null) {
result.compress(Bitmap.CompressFormat.JPEG, 40,
bytes);
}
try {
FileOutputStream fo;
fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
fo.flush();
fo.close();
// result.recycle();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
BitmapDrawable returnResult = new BitmapDrawable(result);
return returnResult;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
} else {
// Here i am getting the out of memory error.
SDdrawable = new BitmapDrawable(BitmapFactory.decodeFile(file
.toString()));
return SDdrawable;
}
}
我认为你没有使用ViewHolder模型对于列表视图。在这种情况下,您应该会收到这样的错误,因为所有列表项都将在内存中可用,无论其是否可见。通过使用 ViewHolder,内存将仅分配给那些可见且当前在屏幕上的项目。ViewHolder模式将性能提高150%有关 ViewHolder 的视频教程请查看this.如果你已经实现了那么就是内存泄漏的情况你可以参考一下this
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)