how to cache images after they are downloaded from web
Convert them into Bitmaps and then either store them in a Collection(HashMap,List etc.) or you can write them on the SDcard.
When storing them in application space using the first approach, you might want to wrap them around a java.lang.ref.SoftReference specifically if their numbers is large (so that they are garbage collected during crisis). This could ensue a Reload though.
HashMap<String,SoftReference<Bitmap>> imageCache =
new HashMap<String,SoftReference<Bitmap>>();
writing them on SDcard will not require a Reload; just a user-permission.
To download an image and save to the memory card you can do it like this.
//First create a new URL object
URL url = new URL("http://www.google.co.uk/logos/holiday09_2.gif")
//Next create a file, the example below will save to the SDCARD using JPEG format
File file = new File("/sdcard/example.jpg");
//Next create a Bitmap object and download the image to bitmap
Bitmap bitmap = BitmapFactory.decodeStream(url.openStream());
//Finally compress the bitmap, saving to the file previously created
bitmap.compress(CompressFormat.JPEG, 100, new FileOutputStream(file));
Don't forget to add the Internet permission to your manifest:
<uses-permission android:name="android.permission.INTERNET" />
I would consider using droidfu's image cache. It implements both an in-memory and disk-based image cache. You also get a WebImageView that takes advantage of the ImageCache library.
Here is the ImageCache library code specifically:
Here is the full description of droidfu and WebImageView: http://brainflush.wordpress.com/2009/11/23/droid-fu-part-2-webimageview-and-webgalleryadapter/
And now the punchline: use the system cache.
URL url = new URL(strUrl);
URLConnection connection = url.openConnection();
connection.setUseCaches(true);
Object response = connection.getContent();
if (result instanceof Bitmap) {
Bitmap bitmap = (Bitmap)response;
}
Provides both memory and flash-rom cache, shared with the browser.
grr. I wish somebody had told ME that before i wrote my own cache manager.