To access shared SharedPreference from service in android
I want to access SharedPreference within my background service i'd used PreferenceManager.getDefaultSharedP开发者_运维问答references()
but it gives nullpoint Exception
Thanks
You have to use the Context like this:
Context ctx = getApplicationContext();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
try this:
SharedPreference pref = getSharedPreferences(PrefName, 0);
If you have created SharedPreferences like:
private static final String PREFS_NAME = "UserData";
private static final String PREFS_VALUE1 = "value1";
then use this:
SharedPreferences preferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
value1 = preferences.getString(PREFS_VALUE1, "default_no");
精彩评论