sbnarra
sbnarra

Reputation: 584

Android Location Manager returning null pointer Exception

I have a issue where I'm trying to create a class that uses the location manager but isn't the currently running activity. So when I call this class from any activity it just does it all in the background. I tried extending Services but keeps returning a null pointer error.

It is this line of code that returns the error.

public class BackgroundGps extends Service{
UserObject uo = null;
BackgroundGps(UserObject userObj){
    uo = userObj;
    uo.setHeader("GPSUpdate");
}
public void locationListener(){
    LocationManager mlocManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
    LocationListener mlocListener = new LocationListener(){
        public void onLocationChanged(Location location){
            if(uo.getLatitude() == ("" + location.getLatitude()) && uo.getLongitude() == ("" + location.getLongitude())){}
            else{
                uo.setLatitude("" + location.getLatitude());
                uo.setLongitude("" + location.getLongitude());
                updateGPS();
            }
        }
        public void onStatusChanged(String provider, int status, Bundle extras) {}
        public void onProviderEnabled(String provider) {}
        public void onProviderDisabled(String provider) {}
    };
    mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 5, mlocListener);
    mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 5, mlocListener);
}

Thanks

Upvotes: 0

Views: 3788

Answers (3)

Arpit Garg
Arpit Garg

Reputation: 8546

Acquire a reference to the system Location Manager

 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

locationManager will not throw a nullpointer on a device, will on a emulator

Register the listener with the Location Manager to receive location updates. Here you can use NETWORK_PROVIDER OR GPS_PROVIDER etc as per your need*

 locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

Upvotes: 1

toto2
toto2

Reputation: 5326

Have you really started the Service using Intents?

If you did not and are just creating a new BackgroundGps() from within your Activity, then the Service has no context (null).

Upvotes: 0

CaseyB
CaseyB

Reputation: 25058

You need to call getSystemService() on the current Context. Are you passing in the current Context when you make calls to this class?

Upvotes: 1

Related Questions