In my Android app, when I run one of my activities a second time, I get an OutOfMemoryError
. I think I need to delete the bitmaps from the first time when the activity runs. But I don't know how I can do this. Thank you.
-
1It's impossible to say what/how you should do as you don't provide enough information. Read up on method `recycle` in class `Bitmap` - maybe, it's what you're after. – Aleks G Jul 13 '12 at 13:38
-
refer this post it will help you http://stackoverflow.com/questions/11410027/android-png-images-big-in-memory/11410131#11410131 – Aerrow Jul 13 '12 at 13:41
3 Answers
Try reading your Bitmaps from within your code. Place the Bitmaps in the res/drawable-hdpi folder. (there are different folders for different image qualities). Set up the Bitmap fields in your code:
Bitmap alpha;
Bitmap foo;
Now initialize the Bitmaps in the onResume():
Options options = new Options();
alpha = BitmapFactory.decodeResource(game.getResources(), R.drawable.youBitmapName, options);
foo = BitmapFactory.decodeResource(game.getResources(), R.drawable.youBitmapName2, options);
Options will give you the ability to downsample. (I'm not sure how big your images are, but you might also want to use the scaling methods then).
In the onPause, clean up resources by calling:
alpha.recycle();
alpha = null;
foo.recycle();
foo = null;
As soon as the onResume() method is called, the bitmaps will reinitialize.

- 9,481
- 13
- 41
- 73
-
I would also put the code to load this in a try...catch block and if an outofmemoryerror is thrown catch it and call System.gc() before retrying or giving up. – ScouseChris Jul 13 '12 at 13:43
Null your bitmaps and call the Garbage Collector: System.gc();
and/or Runtime.getRuntime().gc();
Also provide more details about your code for better answers.

- 6,346
- 6
- 49
- 70
-
-
Yes you can. You can also call it `onResume()`. It depends on your code. – slybloty Jul 13 '12 at 13:46
Normally the garbace collector would call Bitmap.recycle()
as soon as no more references point to that instance.
If you want to 'force' clean up your bitmaps, call recycle()
on your own.
But I would suggest to look for a memoryleak first.

- 1,822
- 14
- 16