Simple Cache Challenge Solution


#1

Here’s my solution to part 1 of the LruCache challenge. I didn’t bother to wrap the cache in its own class, but instead opted to implement it directly within the ThumbnailDownloader class. As a result, no other classes are aware of it. This may prove to be an obstacle for part 2 of the challenge.

Added a constant for LruCache size and a field to hold a reference to the cache object:

private static final int CACHE_SIZE = 4 * 1024 * 1024; // 4MB

private final LruCache<String, Bitmap> mCache;

Instantiate the cache in the ThumbnailDownloader constructor:

	public ThumbnailDownloader(Handler responseHandler) {
		super(TAG);
		mResponseHandler = responseHandler;
		mCache = new LruCache<String, Bitmap>(CACHE_SIZE);
	}

Using the cache in the handleRequest method:

	private void handleRequest(final Token token) {
		final Bitmap bitmap;
		try {
			final String url = requestMap.get(token);
			if (url == null)
				return;
				
			if (mCache.get(url) != null) {	
				bitmap = mCache.get(url);
			} else {
				byte[] bitmapBytes = new FlickrFetchr().getUrlBytes(url);
				bitmap = BitmapFactory
					.decodeByteArray(bitmapBytes, 0, bitmapBytes.length);
				Log.i(TAG, "Bitmap created");
				mCache.put(url, bitmap);	
			}
			
			mResponseHandler.post(new Runnable() {
				@Override
				public void run() {
					if (requestMap.get(token) != url)
						return;
					
					requestMap.remove(token);
					mListener.onThumbnailDownloaded(token, bitmap);
				}
			});
		} catch (IOException ioe) {
			Log.e(TAG, "Error downloading image", ioe);
		}
	}

#2

I think the size of the Lru cache refers to the number of items in it (unless you overwrited sizeOf), not the size in Mb.

Another interesting challenge could be to have the cache survive the life of the application.
Ah, I see.
Support v4 LruCache differs from the normal library LruCache.in that