Load already fetched image when offline in Glide for Android

隐身守侯 提交于 2019-12-07 09:59:23

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/53140975/load-already-fetched-image-when-offline-in-glide-for-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!