我的应用程序有一个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());
行出现了OutOfMemoryErrorE/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)
请帮助我解决此问题。
谢谢!
最佳答案
您不得将位图直接加载到内存中。定义生成的位图应具有的大小,并使用此处描述的技术加载位图的缩放版本:
http://developer.android.com/training/displaying-bitmaps/load-bitmap.html