Code will only return 0.0, 0.0 GPS coordinate while throwing NullPointerException

This tutorial seems like the most promising

It is truly awful code.

I can only seem to get this code to return a GPS coordinate of 0.0, 0.0 which isn’t very useful

That is because it will only ever have a location if getLastKnownLocation() happens to return one. It is unlikely to do so.

Rewritten but still not working permissions block in GPSTracker.java:

There are two problems here:

  1. You cannot request permissions from a service.

  2. This is not a real service. The author of this code elected to create a class that extends Service without actually implementing or using the service properly. This is what is causing your NullPointerException, as this is not a properly initialized Context.

Can anyone please point me in the right direction here?

Throw all of this out.

FWIW, here is my sample app for using the LocationManager API.

The recipe is fairly simple:

Step #1: Get a LocationManager by calling getSystemService(Context.LOCATION_SERVICE) on some Context. I happen to do that in a fragment:

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);

    template=getActivity().getString(R.string.url);
    mgr=(LocationManager)getActivity()
      .getSystemService(Context.LOCATION_SERVICE);
  }

Step #2: Call requestUpdates(), passing in something that implements LocationListener. In my case, that happens to be the fragment itself:

  @Override
  @SuppressWarnings({"MissingPermission"})
  public void onStart() {
    super.onStart();

    mgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3600000,
      1000, this);
  }

Step #3: In onLocationChanged() of your LocationListener, do something with the Location that you get, which in my case is to execute an AsyncTask to get a weather forecast:

  @Override
  public void onLocationChanged(Location location) {
    new FetchForecastTask().execute(location);
  }

Step #4: Call removeUpdates() when you are done:

  @Override
  @SuppressWarnings({"MissingPermission"})
  public void onStop() {
    mgr.removeUpdates(this);

    super.onStop();
  }

And that’s it (other than runtime permission stuff, which I abstract out into an AbstractPermissionsActivity).

If you want, use getLastKnownLocation() as an optimization, but do not rely upon it.

Leave a Comment