Null Pointer with Location Manager

Asked

Viewed 98 times

2

I have the following code which returns NullPointerException on the 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();
    }
}
  • Detail am using Android Studio!

  • That one onLocationChanged() by chance it means that your Activity is implementing LocationListener? Because if it is, the goal is not to call it explicitly but to wait for the GPS to get a new position and call this method without you having to do it (note: this will only happen if before that you call requestLocationUpdates()). This is how you get new positions. The method getLastKnownLocation() only returns the last position obtained that way I spoke, before that it returns nothing even.

  • yes implement Locationlistener! Thank you very much for the tip! ñ had analyzed this possibility.

1 answer

1

You have to do a check if the object is null before trying to access the method of it, something like that:

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

The way Voce is implementing LocationManager, the locationManager.getLastKnownLocation(provider), I don’t know if this is what Voce wants, but here in the documentation has the best ways to do this.

  • Deu Boa! I just need to see that it says that I have the network disabled, Grato1

  • The idea is to update in "Real Time", but I have to move a lot, I’ll take a look at the documentation to implement better!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.