Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Picasso and context

I have been playing lately with Picasso as an image loader library. I use it in conjunction with Dagger and OkHtttp.

My only questions regarding this library are the usage of context and the instantiation of the library through the builder.

I am not entirely sure what it is the context needed (can't find documentation about it) and also which context should we use (ApplicationContext or ActivityContext?) and why.

Looking at examples (btw great example app to see all this in combination) u2020 by Jake Wharton, only a single instance of Picasso it is created with the application context in place. Something like this:

@Provides
    @Singleton
    Picasso providePicasso(@ApplicationContext Context context, OkHttpClient client) {
        Picasso picasso = new Picasso.Builder(context)
                .downloader(new OkHttpDownloader(client))
                .listener(new Picasso.Listener() {
                    @Override
                    public void onImageLoadFailed(Picasso picasso, Uri uri, Exception e) {
                        Log.e("Picasso", "Failed to load image:" + uri);
                    }
                })
                .build();

        return picasso;
    } 

This is use as a global object and only instantiated once. My question is why not instantiating a new picasso instance on Activity level (with the same global OkHttpClient which configures the LRUCache and it is injected previously) and passing the activity as context? I was reading this morning in a Github Picasso thread that Application Context should be used but didn't give more details about it.

So as conclusion, my question are: - What is the context used for and which one should we use. - Why using a global object and not an Activity level instance.

Thanks!

like image 288
Jatago Avatar asked May 29 '14 07:05

Jatago


1 Answers

It doesn't matter which you choose, when using the default Picasso.with(Context) method, or the Builder, it will retrieve the application Context from the given Context:

/** Start building a new {@link Picasso} instance. */
public Builder(Context context) {
  if (context == null) {
    throw new IllegalArgumentException("Context must not be null.");
  }
  this.context = context.getApplicationContext();
}

Stub copied from Picasso.java#Builder.


If you actually want to create a new instance in each activity: For each instance of Picasso you create, you basically create a new cache: images cached in the first instance will not be reused in the second instance. You are very likely to run into OutOfMemoryExceptions here, as Picasso does not handle this.

like image 174
nhaarman Avatar answered Oct 02 '22 15:10

nhaarman