java - 位置值返回 null android

标签 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

最佳答案

请记住,getLastKnownLocation 有时可能返回 null(例如,如果提供商当前已禁用或没有最后的已知位置),因此您应该始终检查此方法的结果:

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

关于java - 位置值返回 null android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23549174/

相关文章:

java - 如何使用Hibernate批处理

java - wsimport - 两个声明导致冲突,给定同一行

android - 在某些版本的 Android 上有选择地启用 Action Bar

android - 关闭 fragment 中的对话框将删除 fragment 本身

java - 如何根据当前日期筛选记录?

java - 如何从远程无状态 session bean 实现接口(interface)?

java - list 合并失败: Attribute application@appComponentFactory cant solve this

java - TeamCity 服务器找不到 java (ubuntu)

android - 创建来自屏幕顶部的 Toast

java - 如何在 ListView 中向具有多个声音的Android onclick添加音频