Skip to content Skip to sidebar Skip to footer

Gps Application Crash

I have to write an application which does several things, including recording the GPS location of the user when a correct username and password is entered. I only want the latitude

Solution 1:

Why getting the BaseContext.. just simply call directly the getSystemService

change this:

LocationManagerlocMan= (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);

to:

LocationManager locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

Solution 2:

locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER); is returning null, which is why you're getting the NullPointerException. Any Context should work in retrieving the LocationManager.

getLastKnownLocation(LocationManager.GPS_PROVIDER) may return null if GPS hasn't been used in the recent past (especially since last reboot).

If a slightly less accurate location (e.g., cell tower level) is acceptable for your application, a better approach is to loop through all LocationProviders and find a non-null location:

publicstatic Location getLocation2(Context cxt) {
    LocationManagermgr= (LocationManager) cxt.getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = mgr.getProviders(true);
    Locationlast=null;
    for (Iterator<String> i = providers.iterator(); i.hasNext(); ) {
        Locationloc= mgr.getLastKnownLocation(i.next());
        // If this provider has a last location, and either:// 1. We don't have a last location,// 2. Our last location is older than this location.if (loc != null && (last == null || loc.getTime() > last.getTime())) {
            last = loc;
        }
    }
    return last;
}

This will use give you the last known GPS position if it is available, and if not, you'll likely get a NETWORK_PROVIDER position.

Note that in rare cases (on normal Android devices) all providers may return null. In this scenario, you'd need to register a LocationListener and wait for a new location to be provided. See https://stackoverflow.com/a/23224818/937715 for a full solution.

Related - for code that takes into consideration the accuracy of each position from each provider, see https://stackoverflow.com/a/21364664/937715.

One final note - you may want to consider using the new(er) fused location provider that is part of Google Play Services, which in my experience is better about always providing a last known location. For sample code that gets the last known location using the fused location provider, see the "Retrieving the Current Location" example.

Post a Comment for "Gps Application Crash"