user90766
user90766

Reputation: 339

pre-cache images using volley

I'm trying to

  1. Pre-load all my images for a grid/list into a disk cache to use later, so that the images can be displayed under poor network conditions. (Think of it like an offline photo gallery)
  2. The cache would only be flushed on demand, never automatically.

I wish to avoid rolling my own code, and want to leverage Volley to the extent possible. Is this possible with 100% volley? If not, can it be achieved through any other library?

Upvotes: 0

Views: 128

Answers (1)

C--
C--

Reputation: 16558

I have not personally used Volley. So, I'm not sure if image caching mechanism is provided by Volley out of the box. Rather, image-loading specific libraries like Picasso provides very elegant pre-caching mechanism for you to use. If you know the list of image URLs upfront, just call the fetch method to start caching files.

// Returns Random Images always. Use your own source instead.
String[] urls = [
    "http://lorempixel.com/400/200",
    "http://lorempixel.com/600/400",
    "http://lorempixel.com/800/600",
    "http://lorempixel.com/300/150",
];

// Prefetch all images
for(String url : urls) {
    Picasso
        .with(getApplicationContext())
        .load(url)
        .fetch();
}

Once Picasso fetches all the images, it will be ready for a load() call from Picasso. Cached images will work just fine even if there is no internet connection.

Picasso
       .with(getApplicationContext())
       .load("http://lorempixel.com/400/200") // Already cached image
       .into(yourImageView);

To add Picasso as a dependency of your project, add the following line to gradle.

compile 'com.squareup.picasso:picasso:2.5.2'

Upvotes: 1

Related Questions