0

I'm not asking for code, I just need some guidance on approaching a problem. I'm new to Android and I'm doing a small project, where I parse JSON from Google Images API to get the url links of images of a certain keyword. I am up to the point where I successfully parsed JSON, made a ListView + ArrayAdapter, and displayed each URL in the Listview. Now I have to figure out how to turn these links into images (I think using bitmaps), and display them in the Listview. I don't want to load them to the SD card because that would use up disk space for each image, but rather store them in the cache. The problem is, I can't use any third-party libraries for caching. I've searched on Google and mostly found things like "LazyLoad" and "Universal Image Loader" but unfortunately they seem to be third-party, not official. I found "LruCache", on the Android Developer website but is the best one for my purposes? Can you let me know what other options I have to solve my problem?

Thank you!

TheEyesHaveIt
  • 980
  • 5
  • 16
  • 33

1 Answers1

1

You have the url for an image. Workflow:

  1. Does image exist on the device already?
    • If so, read it into memory.
    • If not, download it over HTTP(S).
      • Next, save the image somewhere on the disk so you don't have to re-download it next time.
  2. Display this image on the UI.

Don't make it more complicated than it is. Any caching mechanism in Volley, Univeral Image Loader, etc. are just going to build upon this same concept and may be unnecssary for what you want/need to accomplish. Here's some code (albeit slightly dated) that I wrote for a simple app that does exactly this in a very clear manner:

if (!doesCacheFileExist(ctx, filename))
{
    Log.d(TAG, "No cache exists. Downloading.");
    URL url = new URL(uri);

    HttpURLConnection con = (HttpURLConnection) url.openConnection();

    Bitmap b = BitmapFactory.decodeStream(con.getInputStream());

    b = postProcessBitmap(b);

    cacheBitmap(ctx, b, filename);

    return b;
}
else
{
    Log.d(TAG, "Found cached file.");
    return getCachedBitmap(ctx, filename);
}

Full code can be seen here: https://github.com/zaventh/smartsquare/blob/develop/src/com/steelthorn/android/watch/smartsquare/Util.java#L48

Jeffrey Mixon
  • 12,846
  • 4
  • 32
  • 55