SharedPreferenced 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);
The solution i found to this was:
1-In an Activity class (project must have at least one for this solution to work) create a static variable for the context:
public static Context contextOfApplication;
2-In an importante 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);
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.