Prachi
Prachi

Reputation: 2559

To access shared SharedPreference from service in android

I want to access SharedPreference within my background service i'd used PreferenceManager.getDefaultSharedPreferences() but it gives nullpoint Exception

Thanks

Upvotes: 19

Views: 19466

Answers (3)

Harpreet
Harpreet

Reputation: 3070

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");

Upvotes: 3

Jack
Jack

Reputation: 745

You have to use the Context like this:

Context ctx = getApplicationContext();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);

Upvotes: 32

Vineet Shukla
Vineet Shukla

Reputation: 24031

try this:

SharedPreference pref = getSharedPreferences(PrefName, 0);

Upvotes: 6

Related Questions