Question

I am creating a application that stores bitmaps in an array list or in an array. I have set android:largeHeap="true" in the manifest to increase the memory size for the application. I am creating 20 bitmaps and after that if a new bitmap created the first bitmap is recycled (deleted) and new one will be added in the array list. Every time when I add an extra bitmap it releases the memory but after the next 15 to 20 (a total of more than 35) bitmap heap size increased about 20 to 25 MB. This process continues and an out of memory exception occurs. The space not released. I have tried each of the following individually and all together in sequence:

  1. recycle bitmap
  2. assign null
  3. remove from arraylist

The problem is still there.

ArrayList<Bitmap> linesbitmap;

private void touch_start(float x, float y) { // function called on every touch
    if (index >= 19) {
        while (linesbitmap.size() >= 19) {
            linesbitmap.get(0).recycle();
            linesbitmap.remove(0);
        }
        System.gc();
        System.runFinalization();
        System.gc();
    }
    if (mBitmap != null) {
        linesbitmap.add(Bitmap.createBitmap(mBitmap));
    }
    index = linesbitmap.size();
}
Was it helpful?

Solution

When creating and deleting a bitmap in array list or in an array, the heap size increased. I have converted the bitmap to ByteArrayOutputStream and stored that in array list. When we delete or add the new object of ByteArrayOutputStream the heap size does not grow as it did when storing and removing multiple bitmap.

ArrayList<ByteArrayOutputStream> arraylist=new ArrayList<ByteArrayOutputStream>();
new Thread(new Runnable() {
    @Override
    public void run() {
        Bitmap bitmap = Bitmap.createBitmap(mBitmap);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        if (mBitmap != null) {
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            arraylist.add(out);
        }
    }
}).start();

OTHER TIPS

From the question, it looks like you are using the ArrayList as a cache mechanism. If that is the case, you may look at LruCache which is introduced in API Level 12, but is also included in the compatibility package for older API levels.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top