Android: Image Download and Caching
In one of my projects I used a ListView which displayed images from the web and I needed a solution that cached the downloaded images on a device’s external storage. I managed to find a class on the Android website which does exactly that. I modified it slightly to fit my needs(My custom image caching procedures and Android 2.1 compatibility). It has the following features:
- It downloads the image and caches it on the external storage.
- If the external storage device is full, only the image will be returned. No caching will take place.
- If no external storage device is found, it will attempt to cache to the internal storage device.
- It supports multiple downloads at once for multiple ImageViews.
- It keeps track of the download order of the images for ImageViews. (Perfect for ListViews)
- It is also thread safe
Add the WRITE_EXTERNAL_STORAGE permission to your application manifest:
Then initialize the object and use it:
ImageView imgAvatar = (ImageView) convertView.findViewById(R.id.imgAvatar); ImageDownloader imageManager = new ImageDownloader; imageManager.download(expert.ThumbnailFileName, imgAvatar);
The best way to use the ImageDownloader is to create a single instance for your entire application or activity. The images is saved by calculating a hash from the url and then saving the image with the hash as its filename. So when you try to download an image, and the hash already exists, it means that the image is already downloaded and the image is returned from the cache.
Take note that this class was created to compile and run under Android 2.1. It works perfect with the latest Android devices and should be able to compile with the newer Android Platforms.
Update – 26 November 2012
- Fixed out of memory bug that occurs when a lot of images are loaded at once
Here is the download link: ImageDownloader.java
Update – 16 June 2012
If you used the previous version of the ImageDownloader, you might have noticed a slight lag while scrolling through a listview. To improve the lagging, I have added in-memory caching of the images.
Here it is: ImageDownloader v1.01
Ok, I have had a couple of mails and requests about a workspace which implements the image downloader. A proper working example.
Here it is: ImageDownloader Test Workspace