Out Of Memory Exception with custom GridView

This question already has an answer here:

  • Strange out of memory issue while loading an image to a Bitmap object 40 answers

  • 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:

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

  • 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, ie:

    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);
    
    链接地址: http://www.djcxy.com/p/93092.html

    上一篇: 如何减少android的内存消耗

    下一篇: 自定义GridView的内存不足异常