恢复缓存中的图片时,android OutOfMemoryError

时间:2014-06-14 10:34:17

标签: java android android-fragments android-asynctask out-of-memory

我的应用有一个GridView,其中每个项目都是ImageView。我编写了自定义适配器来将图像设置为ImageViews。图像使用AsyncTask异步设置

我的AsyncTask从缓存中恢复图像

@Override
protected Bitmap doInBackground(Void... params) {
   return BitmapFactory.decodeFile(file.getAbsolutePath());
}

@Override
protected void onPostExecute(Bitmap bitmap) {
    if (bitmap != null) {
        imageView.setImageBitmap(bitmap);
    } else {
        // load image from db
    }
}

GridView放在片段上。在服务器片段替换后,我在行BitmapFactory.decodeFile(file.getAbsolutePath());

处得到了一个OutOfMemoryError
E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:299)
            at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
            at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
            at java.util.concurrent.FutureTask.run(FutureTask.java:137)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
            at java.lang.Thread.run(Thread.java:864)
     Caused by: java.lang.OutOfMemoryError: (Heap Size=131079KB, Allocated=126797KB)
            at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
            at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:658)
            at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:347)
            at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:430)
            at com.ThreeBoots.utils.ImageProcessor$2.doInBackground(ImageProcessor.java:248)
            at com.ThreeBoots.utils.ImageProcessor$2.doInBackground(ImageProcessor.java:245)
            at android.os.AsyncTask$2.call(AsyncTask.java:287)
            at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
            at java.util.concurrent.FutureTask.run(FutureTask.java:137)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
            at java.lang.Thread.run(Thread.java:864)

请帮我解决这个问题。 谢谢!

2 个答案:

答案 0 :(得分:1)

您不能将位图直接加载到内存中。定义生成的位图应该是什么尺寸,并使用此处描述的技术加载位图的缩放版本: http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

答案 1 :(得分:0)

首先,您必须在清单中声明大堆大小。并根据您的代码使用位图回收。 对于manifest.xml 机器人:largeHeap ="真"

if (bm != null) {

    bm.recycle();
    bm = null;

}
希望它对你有用。