简体   繁体   中英

LatLng gives null pointer exception

I am working with google maps on android studio. The problem is when i access DriverLatLng 纬度对象 outside 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM