Picasso: How to check if singleton is already set

允我心安 提交于 2020-07-09 07:41:11

问题


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.


回答1:


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"
... >



回答2:


You will have to extend the application class like iagreen mentioned but you should also surround the setUpPicasso method with a try/catch so that if the exception is thrown you can handle it and prevent your application from crashing.

so

package my.package

public class MyApplication extends Application {

@Override
public void onCreate() 
{
    super.onCreate();

    try
    {
        setupPicasso();
    }

    catch ( IllegalStateException e )
    {
        //TODO
    }
}



回答3:


You could also try this.

private static boolean initializedPicasso = false;


if (!initializedPicasso) {
     setupPicasso();
     initializedPicasso = true;
}



回答4:


Surround the setupPicasso() method in a try-catch like so:

try
{
    setupPicasso();
} 
catch (Exception e) 
{
    e.printStackTrace();
}


来源:https://stackoverflow.com/questions/32288546/picasso-how-to-check-if-singleton-is-already-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!