Sajed Ng
Sajed Ng

Reputation: 107

Preventing android volley from caching image

i have Volley network ImageView , problem is when image is changed inside sever volley still uses cached image which is old one , is there anyway that volley understand that image changed inside server ? or if there is't , how can i prevent it from caching ?

here is my current code :

private void networkImage(){
    String url = "http://example.com/profilePictures/"+username+".jpg";

    networkImageView = (NetworkImageView) findViewById(R.id.IBProfilePicture);
    networkImageView.setOnClickListener(this);

    RequestQueue networkQueue = Volley.newRequestQueue(getApplicationContext());
    networkQueue.getCache().remove(url);
    networkQueue.getCache().clear();
    ImageLoader networkImageLoader = new ImageLoader(networkQueue, new ImageLoader.ImageCache() {
        @Override
        public Bitmap getBitmap(String url) {
            return null;
        }

        @Override
        public void putBitmap(String url, Bitmap bitmap) {

        }
    });

    networkImageView.setImageUrl(url,networkImageLoader);
}

Upvotes: 0

Views: 798

Answers (2)

AssIstne
AssIstne

Reputation: 466

  1. changes the server's cache strategy if you can.
  2. you can use request.setShouldCache(false) to disable cache for a request.

for method 2 you can do that by overriding ImageLoader.makeImageRequest();

public class NoCacheImageLoader extends ImageLoader {
    public NoCacheImageLoader(RequestQueue queue, ImageCache imageCache) {
        super(queue, imageCache);
    }

    @Override
    protected Request<Bitmap> makeImageRequest(String requestUrl, int maxWidth, int maxHeight, ImageView.ScaleType scaleType, String cacheKey) {
        Request<Bitmap> request =  super.makeImageRequest(requestUrl, maxWidth, maxHeight, scaleType, cacheKey);
        // key method
        request.setShouldCache(false);
        return request;
    }
}

then use NoCacheImageLoader instead of ImageLoader. Now it will not cache the image into disk.

by the way you should still add timestamp to the url, because if the urls are the same, the NetworkImageView will not load the image again.

Upvotes: 3

mdtuyen
mdtuyen

Reputation: 4548

Try this solution:

private void networkImage(){
    String url = "http://example.com/profilePictures/"+username+".jpg";

    networkImageView = (NetworkImageView) findViewById(R.id.IBProfilePicture);
    networkImageView.setOnClickListener(this);

    RequestQueue networkQueue = Volley.newRequestQueue(getApplicationContext());
    ImageLoader networkImageLoader = new ImageLoader(networkQueue, new ImageLoader.ImageCache() {
        @Override
        public Bitmap getBitmap(String url) {
            return null;
        }

        @Override
        public void putBitmap(String url, Bitmap bitmap) {

        }
    });

    networkImageView.setImageUrl(url+"?time="+System.currentTimeMillis(),networkImageLoader);
}

Upvotes: 3

Related Questions