Android - How to use SharedPreferences in non-Activity class?

后端 未结 12 2374
日久生厌
日久生厌 2020-12-13 08:54

How do you use SharedPreferences in a non-Activity class? I tried making a generic Preferences utility class and importing android.content.Context but Eclipse s

12条回答
  •  别那么骄傲
    2020-12-13 09:13

    The solution i found to this was:

    1-In an MainActivity class (i.e always launched before getting any context in project) create a static variable for the context:

    public static Context contextOfApplication;

    2-In an important method of this class (Such as onCreate, the constructor, etc) initialize this variable using the getApplicationContext method:

    public void onCreate() {
        contextOfApplication = getApplicationContext();
    }
    

    3-In the same class Create a "getter" method for this variable (it must also be static):

    public static Context getContextOfApplication(){
        return contextOfApplication;
    }
    

    4-In the non-activity class get the context by calling the created method statically:

    Context applicationContext = MyActivityClass.getContextOfApplication();

    5-Use the PreferenceManager Class to get the SharedPreferences variable:

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext);
    

    Hope it helps.

提交回复
热议问题