Note that there are some explanatory texts on larger screens.

plurals
  1. POOutOfMemoryError when displaying contacts' photos in Android (bitmap size exceeds VM budget)
    text
    copied!<p>I use the following function to retrieve a contact's photo in Android where the person's lookup key is given:</p> <pre><code>public Bitmap getContactPhoto(String lookup_key) { Uri lookUpUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookup_key); Uri contentUri = ContactsContract.Contacts.lookupContact(ctx.getContentResolver(), lookUpUri); InputStream stream = null; try { stream = ContactsContract.Contacts.openContactPhotoInputStream(ctx.getContentResolver(), contentUri); } catch (Exception e) { } if (stream != null) { return BitmapFactory.decodeStream(stream, null, bitmapOptions); } else { return null; } } </code></pre> <p>When I display those contact photos in a list view, I sometimes read the following error in the developer console's crash reports:</p> <pre><code>Caused by: java.lang.OutOfMemoryError: bitmap size exceeds VM budget(Heap Size=6023KB, Allocated=3002KB, Bitmap Size=27152KB) </code></pre> <p>Does this mean that my app may use about 3MB of heap but a single bitmap had roughly 27MB?</p> <p>I read a lot of questions here on Stack Overflow concerning OutOfMemory error but it was mainly about:</p> <ul> <li>leaking contexts so that the garbage collector cannot free the resources</li> <li>huge bitmaps that need to be scaled</li> </ul> <p>But how can I prevent the error in my case? Since I only get the contacts' photos, I don't know if I have huge bitmaps that must be scaled. And leaking a context doesn't seem to be the case here.</p> <p><strong>This is how the images are displayed:</strong></p> <pre><code>imageView.setVisibility(View.VISIBLE); imageView.setBackgroundResource(R.drawable.background); if (&lt;BITMAP_OBJECT&gt; != null) { imageView.setImageBitmap(&lt;BITMAP_OBJECT&gt;); } else { imageView.setImageBitmap(null); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload