Out Of Memory Exception with custom GridView [duplicate]

断了今生、忘了曾经 提交于 2019-12-01 11:21:42
Paul Lammertsma

You are attempting to allocate too much memory for image data. As you explained in the comments, your images are fairly large and they are being read as soon as the adapter is created.

Reading this into memory will consume 4 bytes per pixel, so if your images are 1024 pixels square, the math is:

  • 1024 × 1024 × 4 = 4MB
  • 15 images × 4 MB/image = 60MB

This likely exceeds the heap budget of 48MB.

You will likely want to improve the efficiency through which you display these images. Consider:

  1. Only loading the image when it is shown, using GridView's mechanisms for getView();
  2. Loading bitmaps with a sample size using BitmapFactory.
Pararth

Esp for "..loading the images in a GridView:
you can use inSampleSize to load all images and replace the visible images by the original ones- meaning for the view part that are visible, dynamically load images without the inSampleSize for the BitmapFactory and its Options.

You could scale them down depending on different devices to load the images without facing a memory problem. In your case, some phones may not exhibit the same behavior on the first run, but eventually, without handling an optimized image loading solution, app will crash.

Topic under Load a Scaled Down Version into Memory.
http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
Out of memory error on Android

On how to avoid them:
How to avoid an out of memory error while using bitmaps in Android

For an overview:
http://blogs.innovationm.com/android-out-of-memory-error-causes-solution-and-best-practices/ http://android-developers.blogspot.de/2009/01/avoiding-memory-leaks.html

Before setting a drawable as the background for your imageview, i.e.:

iv.setBackgroundResource(R.drawable.image);  

Get a scaled bitmap or try other options like inSampleSize, do check how your solution affects the quality of your image too.

For the comment:

Bitmap drawableImage=BitmapFactory.decodeResource(context.getResources(),R.drawable.image);
Bitmap bitmap = Bitmap.createScaledBitmap(drawableImage, width, height, false);
Drawable drawableScaled = new BitmapDrawable(context.getResources(), bitmap);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!