Reputation: 7672
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
Upvotes: 17
Views: 27446
Reputation: 121
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())
Upvotes: -1
Reputation: 9964
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,"");
}
Upvotes: 6
Reputation: 29749
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());
Upvotes: 8