Search code examples
androidbitmapr.java-file

Out of Memory Error in middle of the app, using BitmapFactory option


Application is working till showing image kite then its stopped by giving error OutOfMemory. How to resolve this problem in simple way.

I have 25 images not too large, decoding them through BitmapFactory showing in imageview, want to clear memory of imageview every time before showing the new image on button onClick().

how to do this? how i can use recycle option or array adapter in my app....please anyone help me out of this problem.

MyActivity.java

picasso coding

 Picasso.with(image.getContext())
                        .load(imageIds[currentIndex])
                        .transform(new BitmapTransform(MAX_WIDTH, MAX_HEIGHT))
                        .skipMemoryCache()
                        .resize(size, size)
                        .centerInside()
                        .into(image);

public class BitmapTransform implements Transformation {

    int maxWidth;
    int maxHeight;

    public BitmapTransform(int maxWidth, int maxHeight) {
        this.maxWidth = maxWidth;
        this.maxHeight = maxHeight;
    }

    @Override
    public Bitmap transform(Bitmap source) {
        int targetWidth, targetHeight;
        double aspectRatio;

        if (source.getWidth() > source.getHeight()) {
            targetWidth = maxWidth;
            aspectRatio = (double) source.getHeight() / (double) source.getWidth();
            targetHeight = (int) (targetWidth * aspectRatio);
        } else {
            targetHeight = maxHeight;
            aspectRatio = (double) source.getWidth() / (double) source.getHeight();
            targetWidth = (int) (targetHeight * aspectRatio);
        }

        Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
        if (result != source) {
            source.recycle();
        }
        return result;
    }

    @Override
    public String key() {
        return maxWidth + "x" + maxHeight;
    }

};



@Override
public void onDestroy(){
    super.onDestroy();
    if (mp!=null)
        mp.release();
    finish();
}

}

Solution

  • When it comes to showing images dynamically I am using Picasso library. It handles in single line of code loading scaled images, caching, loading errors etc.

    Picasso.with(context).load(R.drawable.landing_screen).fit().centerInside().into(imageView1);
    

    You can also read Google Developers chapter about Displaying Bitmaps Efficiently if you really need to do it yourself. Definitely, you should move decoding bitmap to the background thread. You can use for that AsyncTask.