I have a custom ListView that does a lazy load of remote images. When you click a listitem, it starts a new Activity and displays the image in a webview.
The problem is, the webview always loads the images, even if the image was preloaded by the listview adapter. I want the WebView to load the image only if it was not preloaded!
Here is how I preload the images in the listview:
public void DisplayImage(String url, ImageView imageView)
{
imageViews.put(imageView, url);
Bitmap bitmap=memoryCache.get(url);
if(bitmap!=null)
imageView.setImageBitmap(bitmap);
else
{
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
The lazy-loaded images are stored in a FileCache:
public FileCache(Context context){
//Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"LazyList");
else
cacheDir=context.getCacheDir();
if(!cacheDir.exists())
cacheDir.mkdirs();
}
public File getFile(String url){
//I identify images by hashcode. Not a perfect solution, good for the demo.
String filename=String.valueOf(url.hashCode());
//Another possible solution (thanks to grantland)
//String filename = URLEncoder.encode(url);
File f = new File(cacheDir, filename);
return f;
}
The proper way to deal with this is to install an
HttpResponseCachewith the client/connection you use for downloading the images. Although a platform implementation wasn’t provided until API level 13, there’s a backported version that works for Android 1.5 and up. This caching mechanism is only suitable forHttp(s)URLConnectionthough; if you useHttpClientyou will want Apache’s HttpClient Caching Module.If you’re after a quick solution, you can potentially also have a look at
WebViewClient‘sshouldInterceptRequest(...)method. By overriding that method, you can intercept requests that get fired whenever a resource is about to be fetched, including images, if I’m not mistaken. You could implement a check that does a local lookup to see if the image has already been downloaded and if so, return it wrapped in aWebResourceResponse. If the file isn’t locally available, simply don’t do anything and let the client handle the downloading. The downside to this is that anything downloaded by the webclient will not be available to the lazy image loader.