Stefan
Stefan

Reputation: 2188

Throwing OutofMemory when setting Bitmap again

I'm using a menu where users can select a category to show. Once a category starts , I'm loading a layer over the background and use this as the resource of my GestureImageView. This works perfectly, but when I do this a couple of times. Going back and forth between the category selection and the map, it throws an OutOfMemory Exception.

This is the method used to create the GestureImageView. The bgverkenning drawable is in every drawable map and sizes are according to 4:6:8:12 (mdpi - hdpi - xhdpi - xxhdpi).

private void loadImageFromStorage(String path, String name)
{

    try {

        File f=new File(path, name);
        BitmapFactory.Options options=new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inSampleSize=2;
    //    options.inJustDecodeBounds = true;
        Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f),null,options);

        BitmapFactory.Options options2=new BitmapFactory.Options();
        options2.inPreferredConfig = Bitmap.Config.RGB_565;

        Drawable laag = new BitmapDrawable(b);
        Bitmap back = BitmapFactory.decodeResource(getResources(), R.drawable.bgverkenning, options2);

        Drawable bg = new BitmapDrawable(back);
        Drawable [] lagen = {bg,laag};
        LayerDrawable ld = new LayerDrawable(lagen);
        map.setImageDrawable(ld);
    }
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }

}

When the activity is stopped, the drawable is deleted.

@Override
protected void onStop() {
    super.onStop();
    Drawable d = map.getDrawable();
    if(d!=null) d.setCallback(null);
    map.setImageDrawable(null);
}

Upvotes: 0

Views: 59

Answers (3)

Cem Philipp Freimoser
Cem Philipp Freimoser

Reputation: 709

As mention before you should use a library. I would recommend Glide its easy to use. Glide LayerDrawable with Glide

Upvotes: 2

Sumit Pathak
Sumit Pathak

Reputation: 529

Use this in Java file

roundBitmap.recycle();

Upvotes: 0

Sebastian Pakieła
Sebastian Pakieła

Reputation: 3029

Bitmaps are really heavy for android. Consider using this library for setting pictures: https://square.github.io/picasso/

Upvotes: 1

Related Questions