Null pointer with Location Manager

2

I have the following code which returns NullPointerException in line: lat = location.getLatitude();

private GoogleMap mMap;
private String provider;
private LocationManager locationManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    double lat =0;
    double lng =0;
    mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    //mMap.addMarker(new MarkerOptions().position(new LatLng(21.000,-51.000)));
    mMap.setMyLocationEnabled(true);
    Criteria criteria = new Criteria();

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    provider = locationManager.getBestProvider(criteria,false);
    if (provider != null){
        Location location = locationManager.getLastKnownLocation(provider);
        lat = location.getLatitude();
        lng = location.getLongitude();
        onLocationChanged(location);
    }else{
        Toast.makeText(this,"Perdemos Você",Toast.LENGTH_LONG).show();
    }
}
    
asked by anonymous 24.05.2014 / 16:46

1 answer

1

You have to do a check if the object is null before trying to access the method itself, something like this:

if(location != null){
  lat = location.getLatitude();
  lng = location.getLongitude();
  onLocationChanged(location);
}

The way you're implementing LocationManager , locationManager.getLastKnownLocation(provider) , searches the last known location of the GPS, I do not know if that's what you want, but here in the documentation have the best ways to do this.

    
24.05.2014 / 16:54