0

I run into the NullPointerException while calling getSystemService(). I checked some posts before but can't figure out why it failed.

public class GetGyroInfo extends Service implements LocationListener{
    private float mLongAccl;
    private float mLatAccl;

    private static final long MIN_TIME_BW_UPDATES = 100; // 100 millisecond

    //Declaring a location manager
    private LocationManager mLocationManager = null;
    private Location mLocation = null;

    private static final String TAG = "ADAS_GetGyroInfo";

    public void getLocation(Context context){

        //Note: getApplicationContext returns NULL inside this constructor. Reason not clear.

        //Create a registor for location updates
        mLocationManager = (LocationManager)  getSystemService(LOCATION_SERVICE);
...
}

The above class is initialized in the following class:

    public class ABCService extends Service {

    ...
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        sendStatusBroadcast(true);

        //Registor location service.
        mgetGyroInfo = new GetGyroInfo();
        mgetGyroInfo.getLocation();
}

I tried the following code and it succeeds:

mgetGyroInfo.getLocation(getApplicationContext());

So my question is, why I have to pass the context from ABCService class to GetGyroInfo? Why can't I get the context inside GetGyroInfo itself?

Till Helge
  • 9,253
  • 2
  • 40
  • 56
Hong
  • 526
  • 6
  • 21
  • 4
    `mgetGyroInfo = new GetGyroInfo();` -- **never** create an instance of an activity or service yourself. – CommonsWare Jul 07 '16 at 14:30
  • 1
    To complete what @CommonsWare said, here is the most basic way to start a Service on Android. First, create an intent : `Intent intent = new Intent(MyActivity.this, MyService.class);` Then start the service : `startService(intent);` – Ephi Jul 07 '16 at 14:36
  • @Ephi, Thanks for the clarification. Obviously the code doesn't follow the way service class should be used. – Hong Jul 07 '16 at 15:00

0 Answers0