Glide v4.4 disable memory cache and disk cache failure - android

The image file is downloaded from the server and always save to the same file name.
So in earlier version of glide, i have been tested with
Uri uri = Uri.fromFile(new File(downloadPath));
GlideApp.with(this)
.load(uri)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(mDownloadImageView);
It seems work for the file with the same name when its image changes. The offical document Glide Caching mentioned like above.
But now in Glide 4.4.0, i used this code again and it is not working. I need to add the signature like below:
Uri uri = Uri.fromFile(new File(downloadPath));
GlideApp.with(this)
.load(uri)
.signature(new ObjectKey(System.currentTimeMillis()))
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(mDownloadImageView);
After adding the signature key, then it works.
Does anyone met the same scenario? DiskcacheStrategy None and skip memory cache true as no effect at all to me.

You have to use the RequestOptions now.
Glide.with(this).load(imageResource)
.apply(RequestOptions()
.placeholder(R.drawable.ic_no_profile_image)
.centerCrop()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.dontAnimate())
.into(profileImageView)

Yes, I have the same problem.
I have to use signature with diskCacheStrategy() set to NONE and skipMemoryCache() set to true if I want to refresh image every time.
Another problem is that if I use diskCacheStrategy() set to ALL with some signature (in order to force cache refresh on some occasions) - it is not working. Signature is changing every time but Glide always loads image from cache and doesn't want to refresh it.
It was working great on Glide v3 and stopped working correctly after upgrading to v4.

Related

Glide Does not use Cached Image

Hi I am using Glide to load image and after following many posts I tried to implement Glide caching using
RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL).centerCrop()
Glide.with(mContext)
.load(imageUrl)
.transition(ImageUtil.crossFadeTransition())
.apply(ImageUtil.requestOptionsForSlider())
.listener(glideRequestListner)
.into(imageView)
My knowledge is that if I use diskCacheStrategy(DiskCacheStrategy.ALL) then the above Glide image loading code will automatically use cache if available, or download if not, right?
But I see everytime the code is called, (checking my internet speed meter) that it is always fetching/downloading from the given url (even though I can see the app memory size is increasing).
I even tried this code also-
val future: FutureTarget<File> = Glide.with(mContext)
.load(imageUrl)
.downloadOnly(500, 500)
Nothing seems to work
What should I do so that Glide uses cache if available?What is wrong with my conception about the caching implementation? Any help is very much appreciated!
Are you sure it is downloading again ? did you try disabling internet just before loading the images ?
Otherwise, is your image URL always the same for the same image ? (as Glide uses it as a cache key).
You can use this in the following calls to check if images are in cache:
Glide.with(fragment)
.load(url)
.onlyRetrieveFromCache(true)
.into(imageView);

How to reload image in Glide from the same url?

I am using Glide image loader to load an image from a specific URL, now if I update the image to the same URL, Glide is still showing the cached image in my imageview. How to reload the image from the same URL?
As per the Glide wiki Caching-and-Cache-Invalidation
Option 1 (Glide v4): Use ObjectKey to change the file's date modified time.
Glide.with(requireContext())
.load(myUrl)
.signature(ObjectKey(System.currentTimeMillis().toString()))
.into(myImageView)
Option 1 (Glide v3): Use StringSignature to change the file's date modified time.
URLs - Although the best way to invalidate URLs is to make sure the server changes the URL and updates the client when the content at the URL changes, you can also use StringSignature to mix in arbitrary metadata
Glide.with(yourFragment)
.load(url)
.signature(new StringSignature(String.valueOf(System.currentTimeMillis()))
.into(yourImageView);
If all else fails and you can neither change your identifier nor keep track of any reasonable version metadata,
Option 2: You can also disable disk caching entirely using diskCacheStrategy() and DiskCacheStrategy.NONE
Glide.with(Activity.this).load(url)
.diskCacheStrategy(DiskCacheStrategy.NONE )
.skipMemoryCache(true)
.into(imageView);
Reference: https://github.com/bumptech/glide/wiki/Caching-and-Cache-Invalidation
Use .diskCacheStrategy(DiskCacheStrategy.NONE)
Glide.with(context)
.load(url)
.apply(new RequestOptions()
.placeholder(R.drawable.placeholder)
.error(R.drawable.error)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true))
.into(ImageView);
Add
signature(new ObjectKey(String.valueOf(System.currentTimeMillis())))
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.cover_placeholder);
requestOptions.error(R.drawable.no_image_available);
requestOptions.signature(
new ObjectKey(String.valueOf(System.currentTimeMillis())));
Glide.with(MosaicFragment.this)
.setDefaultRequestOptions(requestOptions)
.load(finalPathOrUrl)
Use below code, it working fine for me. Set diskCacheStrategy(DiskCacheStrategy.NONE) and skipMemoryCache(true). It will load the image every time.
Glide.with(Activity.this)
.load(theImagePath)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(myImageViewPhoto);
After struggling for a couple of hours, I find the solution.You can mix in the datetime of file by adding StringSignature.So when the file will load,It will always use the latest one.Like this
Glide.with(this)
.load(image_url)
.signature(new StringSignature(String.valueOf(System.currentTimeMillis())))
.into(imageview);
Reference : https://github.com/bumptech/glide/wiki/Caching-and-Cache-Invalidation
I used a work around since no other method worked for me
In my case I knew that when the image on the server will change so I was just adding ?= at the end of the url, for glide it will be a new url and instead of using cache Glide will load the new image.

cache image without showing glide

Is it possible to cache image using glide without showing it in the imageView?. If it is then how?.
Right now I'm doing this code:
Glide
.with(getApplicationContext())
.load("imageUrl")
.override(windowWidth(),(int)windowWidth()*0.5))
.diskCacheStrategy(DiskCacheStrategy.ALL);
But this is not working , when app is open glide load image not from cache but from url.
Since glide 4.X:
//to save img
RequestManager rm = Glide.with(context);
rm.load(imgUrl).submit();
//to load img
Glide.with(context)
.applyDefaultRequestOptions(
new RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL))
.load(imgUrl)
.into(view);
Based on this GitHub topic
i've never used it, but referring the documentation: have you tried the downloadOnly?
Glide's downloadOnly() API allows you to download the bytes of an image into the disk cache so that it will be available to be retrieved later.
https://github.com/bumptech/glide/wiki/Loading-and-Caching-on-Background-Threads#downloadonly
To preload remote images and ensure that the image is only downloaded once:
Glide.with(context)
.load(yourUrl)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.preload();

Glide load thumbnail not working

I'm using Glide to load thumbnail from videos but it doesn't seem to be working on my app. The ImageView is just empty for some reason.
Glide.with(context)
.load(url)
.asBitmap()
.thumbnail(0.1f)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(target);
I added a listener, so I can figure out what is wrong but the Exception thrown is null.
I tried using ThumbnailUtils using the same url because I thought there might be something wrong with it but the thumbnail loads fine.
Anyone experiencing the same? I'm using a Nexus 7 (6.0.1)
Even i stumbled upon the same situation. Somehow from the uri its not loading the image unless create a file instance using local file path. So to make it work i used it like below
Glide.with(mContext).load(Uri.fromFile(new File(path)).into(icon);
In the doc they are using the same approach. You can refer here : Glide - Videos
Apart from that i also noticed unusual behaviour of using the cache. If you are using cache strategy as DiskCacheStrategy.ALL or DiskCacheStrategy.SOURCE it doesn't load the thumbnail but if i am using DiskCacheStrategy.RESULT it works. Hope it helps
As explained in Glide documentation, this feature is only available for videos stored locally on the device.
Also, you should use a path like /storage/emulated/0/Pictures/example_video.mp4. Adding file:/// before this path won't work out either.
You can find more informations here : https://futurestud.io/blog/glide-displaying-gifs-and-videos
Cheers !
You can use override, which surely works:
Glide.with(context)
.load(url)
.crossFade()
.override(width, height)
.into(imageView);
Glide.with(mcontext)
.applyDefaultRequestOptions(RequestOptions.centerCropTransform()
.diskCacheStrategy(DiskCacheStrategy.RESOURCE))
.load(videourl)
.into(thumbnailimg);
Try using this code
#BindingAdapter("videoThumbnailFromUrl")
fun setImageFromVideoUrl(imageView: ImageView, url: String) {
val thumb = 10000L
val options = RequestOptions().frame(thumb)
Glide.with(imageView.context).load(url).apply(options).placeholder(R.drawable.place_holder).into(imageView)
}

Remove image from cache in Glide library

I am using Glide in one of my projects to show image from file.
Below is my code how I am showing the image:
Glide.with(DemoActivity.this)
.load(Uri.parse("file://" + imagePath))
.into(mImage);
The image at this location(imagePath) keeps on changing. By default Glide cache the image it shows in the ImageView. Because of this, the Glide was showing the first image from cache for new images at that location.
If I change the image at location imagePath with some other image having same name then the Glide is showing the first image instead of new one.
Two queries are:
Is it possible to always the image from File and not cache? This way problem will be solved.
Is it possible to clear image from cache before getting newly replaced image? This will also solve the problem.
This is how I solved this problem.
Method 1: When the URL changes whenever image changes
Glide.with(DemoActivity.this)
.load(Uri.parse("file://" + imagePath))
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(mImage);
diskCacheStrategy() can be used to handle the disk cache and you can skip the memory cache using skipMemoryCache() method.
Method 2: When URL doesn't change, however, image changes
If your URL remains constant then you need to use Signature for image cache.
Glide.with(yourFragment)
.load(yourFileDataModel)
.signature(new StringSignature(yourVersionMetadata))
.into(yourImageView);
Glide signature() offers you the capability to mix additional data with the cache key.
You can use MediaStoreSignature if you are fetching content from media store. MediaStoreSignature allows you to mix the date modified time, mime type, and orientation of a media store item into the cache key. These three attributes reliably catch edits and updates allowing you to cache media store thumbs.
You may StringSignature as well for content saved as Files to mix the file date modified time.
As explained in the section Caching and Cache Invalidation of the Glide wiki:
Because File names are hashed keys, there is no good way to simply
delete all of the cached files on disk that correspond to a particular
url or file path. The problem would be simpler if you were only ever
allowed to load or cache the original image, but since Glide also
caches thumbnails and provides various transformations, each of which
will result in a new File in the cache, tracking down and deleting
every cached version of an image is difficult.
In practice, the best way to invalidate a cache file is to change your >identifier when the content changes (url, uri, file path etc).
Since you can't change the file path, Glide offers the signature() API that allows you sets some additional data to be mixed in to the memory and disk cache keys allowing the caller more control over when cached data is invalidated.
If you want to reload every time the image from the disk, you can change your code like this:
Glide.with(DemoActivity.this)
.load(Uri.parse("file://" + imagePath))
.signature(new StringSignature(String.valueOf(System.currentTimeMillis())))
.into(mImage);
There are two ways to handle Glide cache refresh,
Firstway: - Add below with glide implementation
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
Second way:
If you able to identify image changes then give your new file name in below,
.signature(new StringSignature(String.valueOf(fileName)))
or you want to load every time with latest images , use below
.signature(new StringSignature(String.valueOf(System.currentTimeMillis())))
Hope this helps.
This will remove cache memory which is stored by Glide.And it should be done in background otherwise it will throw exception
new Thread(new Runnable() {
#Override
public void run() {
Glide.get(MainActivity.this).clearDiskCache();
}
}).start();
Had troubles with Glide 4.2.0, StringSignature was not resolved.
Looks like StringSignature is not available anymore and you have to use ObjectKey instead.
So code looks like
Glide.with(imageView).
load(pathToImage).
apply(new RequestOptions().signature(new ObjectKey("signature string"))).
into(imageView);
If you save images to the same known filename as a convention and want to invalidate the Glide cache only when the file has changed, using the file modification timestamp can work well.
I was using such a convention for avatar images which I was downloading to File objects outside Glide, and then using Glide just to efficiently resize and make them round, etc.
So I ended up using the StringSignature strategy with the value of the file's lastChanged timestamp as the signature. Here's what the fluent code for that looks like:
Glide.with(this)
.load(avatarFile)
.diskCacheStrategy(DiskCacheStrategy.RESULT)
.signature(new StringSignature(String.valueOf(avatarFile.lastModified())))
.into(ivProfile);
}
where avatarFile is my java.io.File object, of course.
I had troubles with setting signature using Glide version 4.* with Kotlin.
After some time I ended up with this:
fun ImageView.loadUrl(url: String) {
var requestOptions = RequestOptions()
requestOptions.signature(ObjectKey(System.currentTimeMillis()))
Glide.with(this).load(url).apply(requestOptions).into(this)
}
It's an extension function for ImageView, and it's used this way:
imageView.loadUrl(url)
I Hope it will help someone
For Glide 4.3.+ library you need to something like this to ,
Glide.with(context)
.load(image_path)
.apply(new RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true))
.into(imge_view);
In the latest versions we should use RequestOptions
RequestOptions Provides type independent options to customize loads with Glide in the latest versions of Glide.
Make a RequestOptions Object and use it when we are loading the image.
RequestOptions requestOptions = new RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.NONE) // because file name is always same
.skipMemoryCache(true);
Glide.with(this)
.load(photoUrl)
.apply(requestOptions)
.into(profile_image);
I was using Glide to load a File, and here's what I ended up doing to make sure Glide's disk cache was invalidated every time my file changed (even though it had the same path):
Glide.with(context)
.load(bitmapFile)
.signature(new ObjectKey(bitmapFile.lastModified()))
.into(imageView);
I worked on this for days, and all the above-mentioned solutions are just slow as a sloth.
I know you've probably read this before and ignored it because you thought it would probably take a lot of work to change your code. But seriously, it's well worth it. The performance, as far as I can tell, beats all the other methods presented, it's Glide's recommended solution, AND you don't need to skip cache or create signatures so it keeps your code cleaner too.
FROM Glide:
In practice, the best way to invalidate a cache file is to change your
identifier when the content changes (url, uri, file path etc) when
possible. - https://bumptech.github.io/glide/doc/caching.html
SOLUTION:
Change the name of the image when the user uploads a new image. Get the file name and use that for example. Once the image URL has changed, Glide understands you have changed the image and will update the Cache accordingly. This has by far given me the best performance.
WHEN USING:
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
It never caches the images and this really makes images load slowly. You'd think Signatures are better for performance, but to me they seemed just as slow.
signature with GlideApp
GlideApp.with(imageView)
.load(url)
.signature(new ObjectKey(System.currentTimeMillis()))
.placeholder(R.drawable.sky)
.error(R.drawable.sky)
.into(imageView);
And finally Kotlin implementation (For Fragments):
Glide.with(activity)
.load(url)
.apply(RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true))
.into(myImageView)
This worked for me
//use diskCacheStrategy(DiskCacheStrategy.NONE) after skipMemoryCache(true)
Glide.with(this)
.load(image)
.skipMemoryCache(true)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.into(imageview);
Programmatically simply you can use:
// must run on main thread
Glide.get(getApplicationContext()).clearMemory();
// must run in background thread
Glide.get(getApplicationContext()).clearDiskCache();
For More
This one worked for me!
Glide.with(DemoActivity.this)
.load(Uri.parse("file://" + imagePath))
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(mImage);
To benefit from the cache provided by Glide and ensure that the correct image is shown everytime, you can use the signature() API.
All you have to do is to set as signature an information that relates to the image file. When you replace that file, the information changes too and Glide knows it must reload it, ignoring the cache.
A valid information could be a digest (for example SHA-1) calculated on the file contents.
Glide.with(context)
.load(inputFile)
.signature(new StringSignature(sha1(inputFile)))
.into(targetImageView);
Here I found the following implementation of sha1() function:
public static String sha1(final File file) throws NoSuchAlgorithmException, IOException {
final MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
try (InputStream is = new BufferedInputStream(new FileInputStream(file)) {
final byte[] buffer = new byte[1024];
for (int read = 0; (read = is.read(buffer)) != -1;) {
messageDigest.update(buffer, 0, read);
}
}
// Convert the byte to hex format
try (Formatter formatter = new Formatter()) {
for (final byte b : messageDigest.digest()) {
formatter.format("%02x", b);
}
return formatter.toString();
}
}
1) First clear disk cache.
private class ClearGlideCacheAsyncTask extends AsyncTask<Void, Void, Boolean>{
private boolean result;
#Override
protected Boolean doInBackground(Void... params) {
try {
Glide.get(getContext()).clearDiskCache();
result = true;
}
catch (Exception e){
}
return result;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if(result)
Toast.makeText(getActivity(), "cache deleted", Toast.LENGTH_SHORT).show();
}
}
You can call from your ui with new ClearGlideCacheAsyncTask ().execute();
2) Clear memory cache
// This method must be called on the main thread.
Glide.get(context).clearMemory();
Source : https://bumptech.github.io/glide/doc/caching.html
you can use a time stamp, that time could be the file's date modified or System.currentTimeMillis()
this works perfectly
Glide.with(DemoActivity.this)
.load(Uri.parse("file://" + imagePath+"?time="+System.currentTimeMillis()))
.into(mImage);

Categories

Resources