Picasso image cache

4

I'm testing the Picasso library on android in two situations:

1 - When uploading an image, in a url post (without sending% of authentication%), the image is loaded into headers , and ImageView keeps a Picasso if you close cache and open again, the image is cached, 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 activity that has url , 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);

In this second request, I realize that basic auth loads the image correctly, but does not hold any Picasso of it, reloading cache , the image is fetched on the server again (until it returns the result, activity gets the image of ImageView ). Is there any extra configuration required for placeholder to use Picasso when loading an image using memory cache ?

    
asked by anonymous 23.02.2017 / 15:39

1 answer

1

You can resolve this deadlock by using the class Cache , passing it to the OkHttpClient constructor. Simplified as follows:

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 < sup> (en) . See also in this article on OkHttp .

    
26.02.2017 / 02:26