Search code examples
androidpicasso

Why Picasso is not saving image in cache for offline use?


I have following code, which doesnot load image offline as intended. It works online well but I need to load image offline too. I have given permission for Writing external storage too. Any idea will be really helpful.

Picasso.with(getContext())
    .load(userInfo.getUserPictureUri())
    .networkPolicy(NetworkPolicy.OFFLINE)
    .resize(80, 80)
    .error(R.drawable.profile_picture)
    .centerCrop()
    .into(imageView_ProfilePictureSide, new Callback() {
        @Override
        public void onSuccess() {
        }

        @Override
        public void onError() {
            // Try again if cache failed
            Picasso.with(getActivity())
                 .load(userInfo.getUserPictureUri())
                 .error(R.drawable.profile_picture)
                 .into(imageView_ProfilePictureSide);
        }
    });

Solution

  • add the OkHttp to the gradle build file of the app module :

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

    Picasso use the HTTP client request to Disk Cache operation So you can make your own http request header has property Cache-Control with max-age And create your own Static Picasso Instance instead of default Picasso By using Okhttp.

    Both the Okhttp and picasso libraries are provided by squareup team.

    References: How do I use disk caching in Picasso? and Github issue about disk cache, two Questions has been answered by @jake-wharton -> Question1 and Question2