I use the following function to retrieve a contact’s photo in Android where the person’s lookup key is given:
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;
}
}
When I display those contact photos in a list view, I sometimes read the following error in the developer console’s crash reports:
Caused by: java.lang.OutOfMemoryError: bitmap size exceeds VM budget(Heap Size=6023KB, Allocated=3002KB, Bitmap Size=27152KB)
Does this mean that my app may use about 3MB of heap but a single bitmap had roughly 27MB?
I read a lot of questions here on Stack Overflow concerning OutOfMemory error but it was mainly about:
- leaking contexts so that the garbage collector cannot free the resources
- huge bitmaps that need to be scaled
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.
This is how the images are displayed:
imageView.setVisibility(View.VISIBLE);
imageView.setBackgroundResource(R.drawable.background);
if (<BITMAP_OBJECT> != null) {
imageView.setImageBitmap(<BITMAP_OBJECT>);
}
else {
imageView.setImageBitmap(null);
}
When you are setting your
Bitmapto anImageView, try doing this:It may not complete get rid of the problem, but it certainly makes it happen much more rarely.