位置值返回null android

时间:2014-05-08 17:56:59

标签: java android

我试图获取用户的位置并且我有这个方法

public Location getCurrentLocation() {
    LocationManager locManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String provider = locManager.getBestProvider(criteria, true);
    Location location = locManager.getLastKnownLocation(provider);
    return location; 
}

我还有另一种方法可以根据此方法中location变量的纬度和经度将圆形对象居中

private void loadMapResources() {
     userLocation = getCurrentLocation();
     //DRAW CIRCLE HERE
     if(userRadius != 0){
         Circle radiusCircle = googleMap.addCircle(new CircleOptions()
        .center(new LatLng(userLocation.getLatitude(), userLocation.getLongitude()))
        .radius(userRadius)
        .strokeWidth(4)
        .strokeColor(Color.parseColor("#FF6699"))
        .fillColor(Color.parseColor("#66F3F3F3"))
      );
         //SHOW USER ICON AT CURRENT LOCATION
         BitmapDescriptor userIcon = BitmapDescriptorFactory.fromResource(R.drawable.ic_user);
         googleMap.addMarker(new MarkerOptions()
                .title("YOU ARE HERE")
                .icon(userIcon)
                .position(new LatLng(userLocation.getLatitude(), userLocation.getLongitude()))
                );
     }
}

现在,此代码在使用和不使用GPS的设备上都有效。谁能告诉我为什么userLocation会抛出NullPointerException

1 个答案:

答案 0 :(得分:1)

请注意,getLastKnownLocation有时可以返回null(例如,如果提供程序当前已禁用或者没有上一个已知位置),那么您应该始终检查此方法的结果:

Location location = locManager.getLastKnownLocation(provider);
if (location == null){
    //handle this case
    //return location with some default coordinates, for example
}
return location;