Home » Android » android – Picasso Singleton Usage

android – Picasso Singleton Usage

Posted by: admin June 15, 2020 Leave a comment

Questions:

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?

How to&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.

Answer:

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

Answer:

The current method seems to be to use setSingletonInstance

Run this in you application create:

Picasso.setSingletonInstance(Picasso.Builder(context).build()