I am currently working on an android project and that has a user interface to configure a background service.
I have successfully opened and modified the values within the apps preference file but I am then trying to open the shared preference file within the service class but I am getting a null pointer exception.
I’m using the following code to open the file
SharedPreferences settings = this.getSharedPreferences("prefs", 0);
I’m then accessing the shared prefs using the following but when I debug I don’t think it gets this far, I think it fails on the line above.
if (isPowerConnected() && !wakeLock.isHeld() && settings.getBoolean("appEnabled", true))
Below is the exception that is thrown.
10-28 01:02:37.453: E/EnableWakeLock(18665): java.lang.NullPointerException
10-28 01:02:37.453: W/System.err(18665): java.lang.NullPointerException
10-28 01:02:37.453: W/System.err(18665): at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:153)
Thanks for any help you can provide.
Since you try to read a SharedPreferences from a Service you should read it via
instead of
getDefaultSharedPreferences() takes a Context – your Service as a parameter. Please refer to the documentation http://developer.android.com/reference/android/preference/PreferenceManager.html#getDefaultSharedPreferences%28android.content.Context