ZhaoYiLi
ZhaoYiLi

Reputation: 173

LayerDrawable OutOfMemoryError

I need to load 20+ images on top of each other to form an interactive map where each layer can be turned on and off.

I decided to use a LayerDrawable for this, but I keep getting an OutOfMemoryError. Even after I set Large Heap to true, it'll be able to load about 8 images but any more than that it'll still throw the error.

Is there a way to load a lot of images into a LayerDrawable without getting that error, or is there a better way to do this?

Upvotes: 1

Views: 369

Answers (3)

android developer
android developer

Reputation: 116060

using the large heap flag works only on honeycomb and above, and it doesn't promise you anything about how much memory you will get. you could get the same amount as before.

if you wish to load a lot of high quality images, either you scale them down to max of the screen, or use a non-java solution (for example openGL/andengine/lbgdx to show the content) .

if you choose a java solution, you should know that the bare minimum of devices' heap for apps is 16MB . i wish it was larger starting with some sort of android API, but this is not something that you can assume (though i've never seen a new device with such a limitation yet) .

in general , you can assume that your app always has enough memory to hold a bitmap that has the entire screen. you might even assume it always has double than this, but that's it.

if you choose the native other solutions, you are only limited to the device RAM memory, but you are on your own for releasing the memory.

do note that no matter what solution you choose, you are still limited to the amount of memory the device has.

Upvotes: 0

ZhaoYiLi
ZhaoYiLi

Reputation: 173

Thanks to Luksprog's link I was able to fix the problem.

I used inSampleSize to load a smaller version of each of the images before adding them to the Drawable[]. This cut down the amount of memory used by a lot.

Upvotes: 1

marshallino16
marshallino16

Reputation: 2671

Somthing like that ?

Resources r = getResources();
Drawable[] layers = new Drawable[20];
layers[0] = r.getDrawable(R.drawable.01);
layers[1] = r.getDrawable(R.drawable.02);
etc[...]
LayerDrawable layerDrawable = new LayerDrawable(layers);
testimage.setImageDrawable(layerDrawable);

Upvotes: 0

Related Questions