Load already fetched image when offline in Glide for Android

不羁的心 提交于 2019-12-05 14:18:53
aanshu

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