I'm trying to access SharedPreferences in a service.
public class LocationService extends Service implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
Context context = getApplicationContext();
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
...
But I get this error:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate service us.keithirwin.myapp.LocationService: java.lang.NullPointerException
...
Caused by: java.lang.NullPointerException
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:101)
at us.keithirwin.myapp.LocationService.<init>(LocationService.java:31)
...
LocationService.java:31 refers to Context context = getApplicationContext();
.
I used to use this
as context, i.e
PreferenceManager.getDefaultSharedPreferences(this);
That line started coming up null also. My research led me to use getApplicationContext()
as my context. But it's nulls every way I turn.
LocationService.<init>
sounds like the constructor. Other posts seem to say that I can't call preferences there. However, if I try to create sharedPref in onCreate, it's only available in that method. Is there some way to have the preferences available throughout the service?