I am working with google maps on android studio. The problem is when i access DriverLatLngoutside 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
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!