简体   繁体   English

LatLng 给出空指针异常

[英]LatLng gives null pointer exception

I am working with google maps on android studio.我正在 android studio 上使用谷歌地图。 The problem is when i access DriverLatLng问题是当我访问 DriverLatLng 纬度对象 outside onLocationChanged it gives me null pointer exception.在 onLocationChanged 之外,它给了我空指针异常。 My onLocationChanged method is as follows :-我的 onLocationChanged 方法如下:-

@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现在,当我在其他任何地方使用 DriverLatLng 时

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 .在使用DriverLatLng之前,请确保locationlatlon不为空。

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.另请注意,不推荐使用 GoogleApiClient。 You need to use GoogleApi .您需要使用GoogleApi Check out this post .看看这篇文章

Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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