Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid createBitmap() crash in android

I am using createBitmap() in multiple places. Some times this api is throwing OutOfMemoryError() exception. How to avoid this exception?

I am using like below,

createBitamp(width, height, Config.ARGB_8888);

width = width of the screen

height = height of the screen

Any help would be appreciated.

like image 669
pavan Avatar asked Oct 19 '11 15:10

pavan


2 Answers

I have posted some information about how bitmaps are handled in the following Android issue ticket. It might be helpful to you: http://code.google.com/p/android/issues/detail?id=8488#c80

like image 167
Justin Breitfeller Avatar answered Oct 14 '22 18:10

Justin Breitfeller


Many face this problem. You have three ways to solve the proble:

  • Increase available memory: stop services, or change your device to a newer one
  • Decrease memory usage: through optimizing your code
  • [UPDATE] Free up unused Bitmap's memory: call recycle().
  • [UPDATE] Don't use GarbageCollector :)

Usually with Bitmap issues, garbage collector will help.

Justin Breitfeller's response links to a more detailed explanation of the inner workings of the Bitmap. The message to take away is that memory allocated for the bitmap's data (in the native createBitmap method) is treated somewhat separatly, and are not directly freed up by the GarbageCollector when Bitmap becomes garbage collectable. The real solution is to recycle() your bitmaps when not using them. This will still keep the (small) memory allocated for the Bitmap object, but mark the (large) memory allocated for bitmap data garbage collectable. Hence GarbageCollector in turn will free up both, but you don't have to call it manually, before an OutOfMemory occurs, JVM will try to GarbageCollect anyways.

like image 32
Andras Balázs Lajtha Avatar answered Oct 14 '22 17:10

Andras Balázs Lajtha