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

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 still wouldn't let me use getSharedPreferences().


Solution 1:

SharedPreferences are related to context. You can only reference it through a context.

You can simply pass context as a parameter to your class. For example in the constructor.

In your activity do:

MyClass myClass = new MyClass(this);

Solution 2:

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.

Solution 3:

Try using default preferences with an Application context. A context is similar to the environment an application runs in on linux or windows (e.g. environment variables like PATH windowing style or console size). Each Activity and Service has its own Context too for example screen orientation, theme, and label, etc. but for your application you don't want the context of the Activity, you want something global to the app, this is where context.getApplicationContext() is useful. This the same throughout the app and will always give you the same default preferences.