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