Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Picasso Singleton Usage

I am using Picasso in my app.

First, I only use the format below:

Picasso.with(context)....into(imgView);

This way I assume I use Picasso as a singleton. Do I?

Second, I want to use setIndicatorsEnabled. However it cannot be added to the format above since it is not a static method. Is there any way to use this function in the format above?

Third, if I need to create a custom instance using Picasso.Builder(...).build() in order to use setIndicatorsEnabled, what is the best way to achieve singleton usage across the activities of the app?

like image 647
Mehmed Avatar asked Oct 22 '14 16:10

Mehmed


3 Answers

Yes you assume Picasso is a singleton instance when you use Picasso.with(context)....

to use set indicators enabled

Picasso mPicasso = Picasso.with(context);
mPicasso.setIndicatorsEnabled(true);
mPicasso....load().into(imageView);

if you use the builder you should create your own singleton to hold your instance of Picasso and clean it up when your done. Do not use builder every time that you use picasso because it creates a new instance. I believe that Picasso.with(context) just takes your context and calls getApplicationContext and stores a singleton instance of picasso with the application context.

like image 114
doubleA Avatar answered Nov 16 '22 12:11

doubleA


Here is a good way to implement a singleton Picasso class

public class ImageHandler {

    private static Picasso instance;

    public static Picasso getSharedInstance(Context context)
    {
        if(instance == null)
        {
            instance = new Picasso.Builder(context).executor(Executors.newSingleThreadExecutor()).memoryCache(Cache.NONE).indicatorsEnabled(true).build();
        }
        return instance;
    }
}

And then an implementation of it in code would be as follows:

    ImageHandler.getSharedInstance(getApplicationContext()).load(imString).skipMemoryCache().resize(width, height).into(image, new Callback() {
        @Override
        public void onSuccess() {
            layout.setVisibility(View.VISIBLE);
        }

        @Override
        public void onError() {

        }
    });

Note that you don't have to implement the callbacks if not necessary

like image 32
Lord Sidious Avatar answered Nov 16 '22 14:11

Lord Sidious


The current method seems to be to use setSingletonInstance

Run this in you application create:

Picasso.setSingletonInstance(Picasso.Builder(context).build()
like image 35
Calin Avatar answered Nov 16 '22 13:11

Calin