LatLng gives null pointer exception

318 Views Asked by At

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
1

There are 1 best solutions below

0
On BEST ANSWER

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!