In my app I have a list. Once you click an item in that list a new view will be shown. In this view I will display a logo and run some music stream.

The logo is loaded as suggested by Google using the good way of loading an image resource. Actually the image is loaded by URL from my server. but to display I am using the suggested way.

My app is still crashing, actually not when the first time the image has been loaded, but when I go back to the list select an other item. after about 3-4 times switching to an other item the App finally crashes with the out of memory error!

I thought, once a view has been closed, the garbage collector will destroy the loaded image and will just load the new image... but I guess it remains in the memory and after a few loads, it will crash because of not enough memory...

Anyone some suggestions how to solve this? is it possible to clear the memory myself somehow?

有帮助吗?

解决方案

Make sure that before using new Bitmap Image, Recycle the existing Bitmap.

and use setImageDrawable( null );

Try like this,

 ImageView mImage;// YOUR IMAGEVIEW

    Drawable toRecycle = mImage.getDrawable();
            if ( toRecycle != null && toRecycle instanceof BitmapDrawable ) {
                if ( ( (BitmapDrawable) mImage.getDrawable() ).getBitmap() != null )
                    ( (BitmapDrawable) mImage.getDrawable() ).getBitmap().recycle();
            }
   mImage.setImageDrawable( null );

其他提示

Try adding this code when you don't need your bitmaps anymore:

bitmap.recycle();

Make sure no views are referencing the bitmap when you do this.

This will immediately release all memory allocated to the bitmap.

Hope this helps :)

Try this, if your minimum version of sdk is 11 or greater,

add following into application tag in your manifest

android:largeHeap="true"

Hope it will help you.

Add the below code to your bitmap.

   BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize=2;

                Bitmap bmp = BitmapFactory.decodeStream(new FileInputStream(f), null, options);

and also do this code

 Bitmap  correctBmp = Bitmap.createBitmap(bmp, 0, 0, 100, 100, mat, true);

You can change the value 100,100 according to your image quality needed.

Bitmaps are really large objects so you have to load them carefully. Read the guide on the Developer site here. It tells you how you can make sure the system only loads the pixels that are really needed. If you load in the whole image, you can have out of memory exceptions. for example, a 5MP picture will use up to 20MB (4bytes for each pixel) of memory

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top