-1

I am working with google maps on android studio. The problem is when i access DriverLatLngLatLng objectoutside onLocationChanged it gives me null pointer exception. My onLocationChanged method is as follows :-

@Override
public void onLocationChanged(Location location) {
    LastLocation = location;
    double lat = LastLocation.getLatitude();
    double lon = LastLocation.getLongitude();
    DriverLatLng = new LatLng(lat,lon);
    Log.v("data", DriverLatLng.toString());
    mMap.moveCamera(CameraUpdateFactory.newLatLng(DriverLatLng));
    mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}

Now when i use DriverLatLng anywhere else i get

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.android.gms.maps.model.LatLng.toString()' on a null object reference
tomerpacific
  • 4,704
  • 13
  • 34
  • 52
Mohammad Maaz
  • 137
  • 1
  • 8

1 Answers1

2

Make sure location, lat and lon aren't null before you use DriverLatLng.

Try this:

@Override
public void onLocationChanged(Location location) {
    LastLocation = location;
    double lat = LastLocation.getLatitude();
    double lon = LastLocation.getLongitude();
    if(lat == null || lon == null){
       Log.v("nulls", "lat and/or lon are null");
    } else{
       DriverLatLng = new LatLng(lat,lon);
       Log.v("data", DriverLatLng.toString());
       mMap.moveCamera(CameraUpdateFactory.newLatLng(DriverLatLng));
       mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
    }
}

Also, note that GoogleApiClient is deprecated. You need to use GoogleApi. Check out this post.

Hope this helps!

evan
  • 5,443
  • 2
  • 11
  • 20