Can't Access Sharedpreferences From My Service
What I'm trying to do Hello Guys. I got a Service which, set's a boolean to true or to false whenever the service is started or stopped (started = true / stopped = false) in the S
Solution 1:
Here is some code that I'm successfully using in one of my apps. It is used in various parts of the app, e.g. both from activities and services:
voidputValue(Context context, String pref, boolean value) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(pref, value);
editor.commit();
}
booleangetValue(Context context, String value, boolean defaultValue) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, Activity.MODE_PRIVATE);
return settings.getBoolean(value, defaultValue);
}
Solution 2:
Try using getDefaultSharedPreferences(Context context) method of PreferenceManager in both your services and your activities.
privatevoidsetStarted(boolean started) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
mPrefs.edit().putBoolean(PREF_STARTED, started).commit();
Log.d(LOG_TAG, "Variabel " + mPrefs.getBoolean(PREF_STARTED, false));
}
In your Activity
mPrefs = PreferenceManager.getDefaultSharedPreferences(this); run = mPrefs.getBoolean(GPSService.PREF_STARTED, false);
Also make sure you :
- Never call .clear() on editor.
- You use PreferenceManager.getDefaultSharedPreferences(this) everywhere.
Solution 3:
Just build your prefs object the same way you would as part of your activity. The only difference is pulling your application's context in.
SharedPreferencesprefs= _ getApplicationContext().getSharedPreferences("com.example.appname", Activity.MODE_PRIVATE);
BooleantmpBool= prefs.getBoolean("PREF_NAME", null);
Post a Comment for "Can't Access Sharedpreferences From My Service"