Search code examples
androidandroid-lifecyclepicasso

Picasso: How to check if singleton is already set


I am using Picasso for handling image loading in my app. In my Activity I do

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.loading_screen);
    setupPicasso();
    // ...
}

private void setupPicasso()
{
    Cache diskCache = new Cache(getDir(CacheConstants.DISK_CACHE_DIRECTORY, Context.MODE_PRIVATE), CacheConstants.DISK_CACHE_SIZE);
    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setCache(diskCache);

    Picasso picasso = new Picasso.Builder(this)
            .memoryCache(new LruCache(CacheConstants.MEMORY_CACHE_SIZE))
            .downloader(new OkHttpDownloader(okHttpClient))
            .build();

    picasso.setIndicatorsEnabled(true); // For debugging

    Picasso.setSingletonInstance(picasso);
}

This works fine when first starting the app and when pausing the app by pressing the home button. However, when closing the app by pressing the back button, followed by reopening the app, I get the following error:

java.lang.IllegalStateException: Singleton instance already exists.

This happens because Picasso does not allow resetting the global singleton instance. What is the best way to work around this? Is it possible to check if the singleton is already set? Or do I need to keep a member variable in my Activity and check if that is null? Any best practice on this is appreciated.


Solution

  • Call your setupPicasso() method from onCreate in your own Application class. Extend the Application class and override onCreate. Then you will need to add the name attribute to your manifest's <application> section with the fully qualified application class.

    package my.package
    
    public class MyApplication extends Application {
    
    @Override
    public void onCreate() {
        super.onCreate();
        setupPicasso();
    }
    

    Then in your manifest,

    <application 
      android:name="my.package.MyApplication"
    ... >