Picasso cache of images

Asked

Viewed 771 times

4

I’m testing the library Picasso in the android in two situations:

1 - When loading an image, in a url publish (without sending headers authentication), the image is loaded into the ImageView, and the Picasso maintains a cache of this, if it closes the activity and open again, the image is curly, code:

Picasso.with(getContext()).load(
    "http://site.com/imagens/3/download"
)
    .error(R.drawable.imagem_erro)
    .into(imageView);

2 - This time, the image I need to get, is in a url who owns basic auth, code:

        // Adicionar header na request
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .authenticator(new Authenticator() {
                    @Override
                    public Request authenticate(Route route, Response response) throws IOException {

                        return response
                                .request()
                                .newBuilder()
                                .header("Authorization", "abc123")
                                .build();
                    }
                })
                .build();

        // Inserir o OkHttpClient no picasso
        Picasso picasso = new Picasso.Builder(context)
                    .downloader(new OkHttp3Downloader(okHttpClient))
                    .build();

        // Carregar a imagem na imageView setada
        picasso
            .load("http://site2.com/imagem/3/download")
            .error(R.drawable.imagem_erro)
            .placeholder(R.drawable.imagem_placeholder)
            .into(imageView);

On this second request, I understand that the Picasso loads the image correctly, but does not maintain any cache of it, by recharging the activity, the image is fetched on the server again (until it brings the result, the ImageView gets the image of placeholder). Some extra configuration is required so that the Picasso utilize memory cache when uploading an image using basic auth?

1 answer

1

It is possible to resolve this impasse using the class Cache, passing it to the builder of OkHttpClient. Simply like this below:

int cacheSize = 10 * 1024 * 1024; // 10 MiB
Cache cache = new Cache(new File(getApplication().getCacheDir(),"cacheFileName"), cacheSize);
OkHttpClient client = new OkHttpClient.Builder().cache(cache).build();

There are other optimizations you can implement based on in the documentation. See also more details in this article on Okhttp.

  • I implemented this in my code and activated the property 'setIndicatorsEnabled(true)' in Picasso, the displayed indicator is that the image was loaded from disk, but so slow that it seems to have been loaded from the url.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.