Search code examples
androidperformanceandroid-imageviewandroid-drawable

Android how to load drawable images to imageview efficiently


I need to load a bunch of images on the drawable folder to a list of imageview. I'm getting an java.lang.OutOfMemoryError: Failed to allocate a 17280012 byte allocation with 8452164 free bytes and 8MB until OOM error.

Here's the an array file that lists all image names in the drawable folder that needs to be loaded.

 <?xml version="1.0" encoding="utf-8"?>
 <resources>
<string-array name="photo_frames">
    <item>pf1</item>
    <item>pf2</item>
    <item>pf3</item>
    <item>pf4</item>
    <item>pf5</item>
    <item>pf6</item>
    <item>pf7</item>
    <item>pf8</item>
    <item>pf9</item>
    <item>pf10</item>
    <item>pf11</item>
    <item>pf12</item>
     </string-array>
 </resources>

Here's the code for the listAdapter to load the image, photoFrames is an array that holds the image names.

public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        //Layout inflate for list item
        convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item_photo_frames, null);
    }

    ImageView imgPhotoFrames = (ImageView) convertView.findViewById(R.id.image_photo_frames);
    imgPhotoFrames.setImageResource(mContext.getResources().getIdentifier(photoFrames[position], "drawable", mContext.getPackageName()));


    return convertView;
}

If I have a few images it loads fine, but it is kind of lag. When there are more images to be loaded to imageView, then it return an error, Thanks.


Solution

  • 17280012 bytes is the equivalent of a 2078 x 2078 pixel image. This is larger than the resolution of most device screens. You should be loading 0-1 of these images at a time, not 12 of them.

    If your images have a high resolution like that, lower their resolution.

    If your images have a lower resolution already, but you put them in res/drawable/, either move them to res/drawable-nodpi/ or plan on creating different editions of the drawables for different densities. No bitmaps belong in res/drawable/, as that is just a synonym for res/drawable-mdpi/, and so Android will resample the images on higher-density screens.