2

I would like to use Android's system cache when downloading images as per these previous instructions: android system cache. I was able to get the following code working but the log statements are telling me that the images are never being read from the cache.

try {
    //url = new URL("http://some.url.com/retrieve_image.php?user=" + username);
    URL url = new URL("http://some.url.com/prof_pics/b4fe7bdfa174ff372c9f26ce6f78f19c.png");
    URLConnection connection = url.openConnection();
    connection.setUseCaches(true);
    Object response = connection.getContent();
    if (response instanceof Bitmap) {
        Log.i("CHAT", "this is a bitmap");
        current_image.setImageBitmap((Bitmap) response);
    }
    else {
        Log.i("CHAT", "this is not a bitmap");
        Log.i("CHAT", response.toString());
        InputStream is = connection.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        current_image.setImageBitmap(BitmapFactory.decodeStream(bis));
    }
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

I have tried two different types of requests, one is to go through a PHP script that returns the image and another that is directly accessing the image file. I refresh the same image multiple times in a row and it never seems to get cached. For the direct image access, I get:

05-31 23:45:12.177 I/CHAT    ( 2995): this is not a bitmap
05-31 23:45:12.177 I/CHAT    ( 2995): org.apache.harmony.luni.internal.net.www.protocol.http.FixedLengthInputStream@40c1c660`

For the indirect image access, I consistently get:

05-31 23:45:14.550 I/CHAT    ( 2995): this is not a bitmap
05-31 23:45:14.550 I/CHAT    ( 2995): org.apache.harmony.luni.internal.net.www.protocol.http.ChunkedInputStream@40c02448
Community
  • 1
  • 1
ravishi
  • 3,349
  • 5
  • 31
  • 40

1 Answers1

4

I found a better way to do it. If anyone else is having trouble after following the link android system cache, use this Google developer's blog post instead. The source code in that blog post is designed for a ListView but I am using it for all image retrievals. It downloads the image in an AsyncTask, puts a temporary image while downloading, and has an image cache. This last part is listed as a "Future Item" in the blog post, but if you download the source code, the cache is implemented. I had to modify the code slightly because the AndroidHttpClient isn't supported in 2.1. I switched it to a URL connection. So far, this looks to be a great image downloader class. Let's just hope it doesn't impact our already struggling memory management issues.

Community
  • 1
  • 1
ravishi
  • 3,349
  • 5
  • 31
  • 40