Home > Tutorials > Bitmap and memory leak! – Part 3

Bitmap and memory leak! – Part 3


After my previous post on Bitmap and memory leak! – Part 2, some buddies ask me how to free memory of Bitmap on a HashMap storage.

Pretty much simple:

package pete.android.study;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import android.graphics.Bitmap;

public class BitmapStorage {

	HashMap<Integer, Bitmap> mStorage;

	// constructor to create the objects
	public BitmapStorage(HashMap<Integer, Bitmap> storage) {
		mStorage = storage;

	}

	// call in order to free memory of Bitmap objects
	public void clear() {
		// get HashMap entry iterator
		Iterator<Entry<Integer, Bitmap>> iter = mStorage.entrySet().iterator();
		while(iter.hasNext()) {
			// get entry pair
			Entry<Integer, Bitmap> pair = iter.next();
			// get Bitmap object
			Bitmap image = pair.getValue();
			// recycle if...
			if(image != null && !image.isRecycled()) {
				image.recycle();
				image = null;
			}
		}

		mStorage.clear();
	}

	// the destructor should also handle the memory in case it still holds memory
	protected void finalize() {
		clear();
	}

}

Do the same for even complex data structure in HashMap implementation.

package pete.android.study;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import android.graphics.Bitmap;

public class BitmapStorage {

	// even a complex data structure containing Bitmap objects
	private class CustomDataHolder {
		String content;
		Bitmap image;
	}

	HashMap<Integer, CustomDataHolder> mStorage;

	// constructor to create the objects
	public BitmapStorage(HashMap<Integer, CustomDataHolder> storage) {
		mStorage = storage;

	}

	// call in order to free memory of Bitmap objects
	public void clear() {
		// get HashMap entry iterator
		Iterator<Entry<Integer, CustomDataHolder>> iter = mStorage.entrySet().iterator();
		while(iter.hasNext()) {
			// get entry pair
			Entry<Integer, CustomDataHolder> pair = iter.next();
			// get Bitmap object
			Bitmap image = pair.getValue().image;
			// recycle if...
			if(image != null && !image.isRecycled()) {
				image.recycle();
				image = null;
			}
		}

		mStorage.clear();
	}

	// the destructor should also handle the memory in case it still holds memory
	protected void finalize() {
		clear();
	}

}

 

Cheers,
Pete Houston

Advertisements
Categories: Tutorials Tags: , , ,
  1. April 1, 2012 at 1:53 pm

    ok. thanks

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: