How can I 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've tried SoftReferences, they are too aggressively reclaimed in android that I felt there was no point using them
Late answer but I think this library will help a lot with caching images : https://github.com/crypticminds/ColdStorage.
Simply annotate the ImageView with @LoadCache(R.id.id_of_my_image_view, "URL_to_downlaod_image_from) and it will take care of downloading the image and loading it into the image view. You can also specify a placeholder image and loading animation.
Detailed documentation of the annotation is present here :- https://github.com/crypticminds/ColdStorage/wiki/@LoadImage-annotation