7

Am using Glide version 4.8.0

And for loading an image I do this

GlideApp
    .with(HomePageFragment.this)
    .load(remoteURL)
    .diskCacheStrategy(DiskCacheStrategy.ALL)
    .into(mImageView);

When the device is connected to Internet the image loades successfully but when device goes offline, how to load the same image from cache that was already featched from the remoteURL?

My CustomAppGlideModule looks like this

@GlideModule
public class CustomAppGlideModule extends AppGlideModule {

    @Override
    public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) {
        builder.setMemoryCache(new LruResourceCache(20 * 1024 * 1024));
        builder.setDiskCache(new InternalCacheDiskCacheFactory(context, 100 * 1024 * 1024));
    }

}

I also tried

.onlyRetrieveFromCache(true)

But that also does not help.

kanudo
  • 2,119
  • 1
  • 17
  • 33

1 Answers1

8

Option 1: Use DiskCacheStrategy.SOURCE instead of DiskCacheStrategy.ALL it should work because of DiskCacheStrategy.SOURCE saves the original data to cache.

//Version 4.x
GlideApp
    .with(HomePageFragment.this)
    .load(remoteURL)
    .diskCacheStrategy(DiskCacheStrategy.DATA)
    .into(mImageView);

//Version 3.x
Glide.with(mContext)
   .load(url)
   .diskCacheStrategy(DiskCacheStrategy.SOURCE)
   .into(imageView);

Option 2: (if above does not work)

Any specific reason for using Glide? Would you like to give a shot to Picasso, I found Picasso much better for this. You may use the following code for offline caching. It will first serve from offline if not found then search for online image.

Picasso.with(getActivity())
.load(imageUrl)
.networkPolicy(NetworkPolicy.OFFLINE)
.into(imageView, new Callback() {
    @Override
    public void onSuccess() {
      //..image loaded from cache
    }

    @Override
    public void onError() {
        //Try again online if cache failed
        Picasso.with(getActivity())
                .load(posts.get(position).getImageUrl())
                .error(R.drawable.header)
                .into(imageView, new Callback() {
            @Override
            public void onSuccess() {
              //... image loaded from online
            }

            @Override
            public void onError() {
                Log.v("Picasso","Could not fetch image");
            }
        });
    }
});
kanudo
  • 2,119
  • 1
  • 17
  • 33
aanshu
  • 1,602
  • 12
  • 13
  • Thanks for your answer, actually i found the error, it was at some other place. And yes I use glide cause it does not require to resize image for `centerCrop()` and also provide many other built in facilities. AND the most important is the caching mechanism of it. – kanudo Nov 04 '18 at 14:12
  • oh thanks for sharing the knowledge. Can you please edit the answer, with the solution you found to make this question productive for others. If you found helpful please upvote. – aanshu Nov 04 '18 at 14:15