pavan
pavan

Reputation: 1135

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.

Upvotes: 7

Views: 8396

Answers (2)

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.

Upvotes: 5

Justin Breitfeller
Justin Breitfeller

Reputation: 13801

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

Upvotes: 6

Related Questions