I have a list view with 100 different images. My cache looks like the following,
public class ImageCache {
HashMap<String, SoftReference<Drawable>> myCache;
....
....
public void putImage(String key, Drawable d) {
myCache.put(key, new SoftReference<Drawable>(d));
}
public Drawable getImage(String key) {
Drawable d;
SoftReference<Drawable> ref = myCache.get(key);
if(ref != null) {
//Get drawable from reference
//Assign drawable to d
} else {
//Retrieve image from source and assign to d
//Put it into the HashMap once again
}
return d;
}
}
I have a custom adapter in which I set the ImageView's icon by retrieving the drawable from my cache.
public View getView(int position, View convertView, ViewGroup parent) {
String key = myData.get(position);
.....
ImageView iv = (ImageView) findViewById(R.id.my_image);
iv.setImageDrawable(myCache.getImage(key));
.....
}
But when I run the program, most of the images from the ListView disappears after a while and some of them are not even there at the first place. I replaced the HashMap with a hard reference instead. Like,
HashMap<String, Drawable> myCache
And that piece of code works. I want to optimize my code. Any suggestions.