Handle null values when using Android’s LocationManager

I’d noticed a number of fatal app crashes recently, and it was only through luck I discovered that I wasn’t handling null values that were being returned by the device’s  LocationManager. I only discovered this through a bit of detective work and being lucky enough to have the app crash while hooked up to logcat when the device decided to act up. I can now say with certainty that it’s true a GPS_PROVIDER or LOCATION_PROVIDER can indeed return null values. So, as a best practice  now I simply listen for them and handle them gracefully.

I’ve also noticed that sometimes these null values can happen sporadically, so I’ve also implemented a counter system that says if a certain number of null values happen in a row then shut down the LocationManager and notify the user, otherwise simply ignore them. Here’s an example of the basic pattern:

// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {

	int counter = 0;

	public void onLocationChanged(Location location) {
      // Called when a new location is found by the network location provider.
		if(location != null){
			counter = 0
			double lat = loc.getLatitude();
			double lon = loc.getLongitude();
		}
		else
		{
			counter++;
			if(counter > 3)
			{
				// Remove the listener you previously added
				locationManager.removeUpdates(locationListener);
                                //locationManager = null;

				//Let user know there was a problem and that GPS was shut off....
			}

		}
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {}

    public void onProviderEnabled(String provider) {}

    public void onProviderDisabled(String provider) {}
};

// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

Here’s one example of a GPS problem on a Motorola Atrix in logcat:

06-01 15:15:43.298: E/libgps(1653): recv_command_nmea() : NMEA_PARSE_ERROR_DATA_FIELDS_MISSING: The sentence does not contain enough fields for its data type