Android - using Singleton to access hold application settings, and Context

那年仲夏 提交于 2019-12-07 16:05:41
Jean-Philippe Roy

As far as sharing information between Activities, you pretty much have two options:

  1. Singleton Class, like you suggested.
  2. Extend the Application class and store your information there (which to my limited knowledge, is some sort of buffed Singleton).

Personally I use Singletons to manage Application Scoped Information in my Android applications. I'd like to give you the pros and cons to both approach myself but it's been debated heavily all over the internet ;) This question answered all my question when I got into Android programming and was trying to figure out how to shared information in my application in the most intelligent way possible.

I, personally never had any problems passing my Context to Singletons in order for them to do work related to Shared Preferences. I guess you've just have to be careful about what you're doing, like anything you're coding really.

You can try:

public class SomeApplication extends Application {


    private static SomeApplication _instance;

    public SomeApplication() {
       super();
    }

    public static SomeApplication getInstance() {
       return _instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();  
        _instance = this;
    }

    public SharedPreferences getPreferences() {
         return getApplicationContext().getSharedPreferences( SOME_PREFS_KEY, Context.MODE_PRIVATE );
    }

}

    .....
       SharedPreferences prefs =  SomeApplication.getInstance().getPreferences();
    ..... 

Don't forget about manifest.xml

    <application android:label="@string/app_name" android:icon="@drawable/icon"
             android:name="SomeApplication"
       >
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!