Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Glide Image cache with id not url

I am working in Android app that load images from Amazon S3. The Image URL randomly changes with token and expiry key. For that reason i can't cache the image Glide.

There is any way to set Glide cache key as any static ID(like image id) not url.

I attached my code snippet to load image from AWS

Glide.with(remoteGalleryAct).load(photoFinalImageURL)
                .signature(new StringSignature(getImageUrl(photoFinalImageURL)))// remove AWS keys
                .error(defaultNoImageDrawable)
                .placeholder(defaultNoImageDrawable)
                .dontAnimate()
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .into(new ImageViewTarget<GlideDrawable>(photoHolder.photo) {
                    @Override
                    protected void setResource(GlideDrawable resource) {
                    }

                    @Override
                    public void onResourceReady(final GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
                        //super.onResourceReady(resource, glideAnimation);
                        view.setImageDrawable(resource);
                    }
                });

Please suggest me there is any way to achieve in Glide.

like image 723
user968571 Avatar asked Nov 11 '16 15:11

user968571


People also ask

Does glide cache images by default?

Glide will put all image resources into the memory cache by default.

How does glide caching work?

How does the Glide caching mechanism work? By default, Glide uses memory and disk caching to avoid unnecessary network calls, it checks into multiple layers of caches before initiating a new request call for an image.


1 Answers

Override getCacheKey() method of GlideUrl class. This method sets the key for caching the image.

Here's how to do it:

//Create a custom class and override the method to remove authentication header from the S3 image url

public class GlideUrlCustomCacheKey extends GlideUrl {
    public GlideUrlCustomCacheKey(String url) {
        super(url);
    }

    public GlideUrlCustomCacheKey(String url, Headers headers) {
        super(url, headers);
    }

    public GlideUrlCustomCacheKey(URL url) {
        super(url);
    }

    public GlideUrlCustomCacheKey(URL url, Headers headers) {
        super(url, headers);
    }

    @Override
    public String getCacheKey() {
        String url = toStringUrl();
        if (url.contains("?")) {
            return url.substring(0, url.lastIndexOf("?"));
        } else {
            return url;
        }
    }
}

Set the imageView with the URL obtained from this class:

Glide.with(context).load(new GlideUrlCustomCacheKey(buzzUrl)).into(imageView);
like image 178
Avinash Gupta Avatar answered Oct 31 '22 12:10

Avinash Gupta