19

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

Thanks

2
  • show me your code..... than i can explain where problem come... Sep 7, 2011 at 12:23
  • 1
    Yes I don't think many people will be eager to help if you have a track record of never acknowledging it.
    – Joel F
    Sep 7, 2011 at 12:54

3 Answers 3

32

You have to use the Context like this:

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

try this:

SharedPreference pref = getSharedPreferences(PrefName, 0);
1
  • SharedPreference should be SharedPreferences (missing s). I tried to edit it directly but website doesn't allow editing less than 6 letters.
    – clueless
    Nov 21, 2021 at 5:23
3

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");
1
  • More better option than this is to create a singleton Preferences class to store and retrieve values from SharedPreferences.
    – Harpreet
    Sep 5, 2016 at 11:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.