When working with bitmaps, there is an issue that shows in the device but not in the
android emulator.
I was always thinking that after using the method empty(), I did not have to worry about the reference variable no more. I did this assumption because in the android developers guide like establish that “Free the native object associated with this bitmap, and clear the reference to the pixel data.” (http://developer.android.com/reference/android/graphics/Bitmap.html). Therefore, I was assuming that the Garbage Collector would take care of it:
Bitmap bitmap = null; bitmap = BitmapFactory.decodeFile(uri.getPath()); if (bitmap != null) { ... bitmap.recycle(); } ..However, I was proven wrong after repeated problem I was facing when running the program inside the device.
After searching online for hours, I found out that the bitmap reference have to be set to null after using the recycle() method:Bitmap bitmap = null; bitmap = BitmapFactory.decodeFile(uri.getPath()); if (bitmap != null) { ... bitmap.recycle(); bitmap = null; } ...Just to clarify, there is no obligation in using the recycle() method; however, it is a good practice using it.
Another thing to have in consideration is that when you pass a bitmap object to another object, you need to know if that object would make a copy or use the bitmap object that you provide. If the bitmap object provided is the one that will be use, then make sure to not recycle or null the bitmap object else you will get a run-time error.
Bitmap bitmap = null; bitmap = BitmapFactory.decodeFile(uri.getPath()); if (bitmap != null) { imageButtonPicture.setImage(bitmap); // do not null or recycle bitmap } ...© 2011, Alejandro G. Carlstein Ramos Mejia. All rights reserved.