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.
To simply load an image to LinearLayout, we call the with() method of Glide class and pass the context, then we call the load() method, which contains the URL of the image to be downloaded and finally we call the into() method to display the downloaded image on our ImageView.
How Glide Cache Works. By default, Glide checks multiple layers of caches before starting a new request for an image: Active resources — Is this image displayed in another View right now? Memory cache — Was this image recently loaded and still in memory?
Glide enables effective loading and caching of images. You can load images from a variety of sources such as files URIs, Android resources, bitmaps, drawables, etc. Just use the load() method to receive images.
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");
}
});
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With