I have read question : this and this about reading shared preferences. But they still need Context to access SharedPreferences. I want to know how to access SharedPreferences without context. Thanks in advance
Asked
Active
Viewed 2.6k times
17
-
6You simply _can't_, but as long as your application is running there is an _Application Context_ available to be used... – K-ballo Jun 29 '12 at 20:39
-
You can't. It needs a context. – Cruceo Jun 29 '12 at 20:40
-
If you can elaborate on why you need it that way, maybe we can help you more with that. – Erol Jun 29 '12 at 20:40
-
I built my own library very long time ago, full of static methods. But now, I want to modify that library to save some user preferences. I can pass context every static method call, but that will force me to refactor entire classes in my application. – Niyoko Jun 29 '12 at 20:44
-
@K-ballo: How to get ApplicationContext? – Niyoko Jun 29 '12 at 20:48
-
I do not think you will have to refactor. Inside your class, use the getApplicationContext() method and store it as a static class variable. Then use this Context variable in the static methods where you are using SharedPreferences. – Erol Jun 29 '12 at 20:56
4 Answers
8
Application Class:
import android.app.Application;
import android.content.Context;
public class MyApplication extends Application {
private static Context mContext;
public void onCreate() {
super.onCreate();
mContext = getApplicationContext();
}
public static Context getAppContext() {
return mContext;
}
}
Declare the Application in the AndroidManifest:
<application android:name=".MyApplication"
...
/>
Usage:
PreferenceManager.getDefaultSharedPreferences(MyApplication.getAppContext());

Oded Breiner
- 28,523
- 10
- 105
- 71
-
10context is a big data, its not good that be a static object(memory leak and...) – Abbas Torabi Sep 25 '19 at 13:15
-
5
We can have SharedPreference instance to use in a helper class having Getters and Setters, Without involving context explained here
In MainActivity add
public static SharedPreferences preferences;
preferences = getSharedPreferences( getPackageName() + "_preferences", MODE_PRIVATE);
Then in PreferenceHelper use set and get as
public static void setName(String value) {
MainActivity.preferences.edit().putString(KEY_DEMO_NAME, value ).commit();
}
public static String getName() {
return MainActivity.preferences.getString(KEY_DEMO_NAME,"");
}

Code Spy
- 9,626
- 4
- 66
- 46
0
Oded's answer got me what I needed for my callback method in my utility class. In my case I needed a kotlin version which looks like this.
manifest
android:name=".SGAutoApp"
SGAutoApp.kt
class SGAutoApp : Application() {
companion object {
fun getAppContext(): Context {
return this.getAppContext()
}
}
}
and then it's like below in my utility class callback method.
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(SGAutoApp.getAppContext())

80sTron
- 59
- 1
- 5