kanudo
kanudo

Reputation: 2219

Load already fetched image when offline in Glide for Android

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.

Upvotes: 8

Views: 6588

Answers (1)

aanshu
aanshu

Reputation: 1602

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");
            }
        });
    }
});

Upvotes: 9

Related Questions