Search code examples
androidimagecachinguniversal-image-loader

How to cache images using dynamic image URIs?


How can I setup the Android Universal Image Loader to load dynamic image URIs?

For instance:

Both URIs must be representing the same remote image image.jpg:

Reference:

Sometime, you may not want to use the image URL as cache key because part of the URL is dynamic (i.e.: for access control purpose)

SDWebImage - Using cache key filter

I am using the SDWebImage inside my iOS application and I really need a similar feature to be able to use the UIL inside its Android version.


Solution

  • I think you can use this memory cache decorator:

    public class CustomMemoryCache implements MemoryCacheAware<String, Bitmap> {
    
        private final MemoryCacheAware<String, Bitmap> cache;
    
        public CustomMemoryCache(MemoryCacheAware<String, Bitmap> cache) {
            this.cache = cache;
        }
    
        @Override
        public boolean put(String key, Bitmap value) {
            return cache.put(cleanKey(key), value);
        }
    
        @Override
        public Bitmap get(String key) {
            return cache.get(cleanKey(key));
        }
    
        @Override
        public void remove(String key) {
            cache.remove(cleanKey(key));
        }
    
        @Override
        public Collection<String> keys() {
            return cache.keys();
        }
    
        @Override
        public void clear() {
            cache.clear();
        }
    
        private String cleanKey(String key) {
            return key.substring(0, key.lastIndexOf("?")) + 
                     key.substring(key.lastIndexOf("_")); 
                // original cache key is like "[imageUri]_[width]x[height]"
        }
    }
    

    Then wrap any ready memory cache implementation and set it into the configuration. For example:

    LruMemoryCache memoryCache = new LruMemoryCache(memoryCacheSize);
    CustomMemoryCache memoryCacheDecorator = new CustomMemoryCache(memoryCache);
    
    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
        ...
        .memoryCache(memoryCacheDecorator)
        ...
        .build();