Search code examples
androidimage-caching

Images are not stored in the cache


I have this method, everything is worked perfectly but images always got from server and not load from cache! what happened ?

public static void makeImageRequest(String Unique_ID, final View parentView, final int id) {

    String url = FILE_UPLOAD_FOLDER + Unique_ID + ".png";
    final int defaultImageResId = R.drawable.user;
    // Retrieves an image specified by the URL, displays it in the UI.  
    ImageCacheManager.getInstance().getImage(url, new ImageListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            ImageView imageView = (ImageView) parentView.findViewById(id);
            imageView.setImageResource(defaultImageResId);
        }

        @Override
        public void onResponse(ImageContainer response, boolean isImmediate) {
            if (response.getBitmap() != null) {
                ImageView imageView = (ImageView) parentView.findViewById(id);
                imageView.setImageBitmap(response.getBitmap());
            } else if (defaultImageResId != 0) {
                ImageView imageView = (ImageView) parentView.findViewById(id);
                imageView.setImageResource(defaultImageResId);
            }

        }
    });
}

Solution

  • Just use Picasso instead ImageCacheManager. Picasso is a powerful image downloading and caching library for Android. Images add much-needed context and visual flair to Android applications. Picasso allows for hassle-free image loading in your application—often in one line of code!

    Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
    

    Here also can manage whether the image is successfully downloaded or it fails:

                        Picasso.with(context)
                                    .load("http://i.imgur.com/DvpvklR.png")
                                    .into(imageView, new Callback() {
                                        @Override
                                        public void onSuccess() {
                                            // your code
                                        }
    
                                        @Override
                                        public void onError() {
                                            // your code
                                        }
                                    }); 
    

    You should only add this line in your gradle:

    compile 'com.squareup.picasso:picasso:2.5.2'
    

    Hope it helps!