在获取当前纬度和经度时获取空对象引用 [重复]

Posted

技术标签:

【中文标题】在获取当前纬度和经度时获取空对象引用 [重复]【英文标题】:Geting a nul Object Reference in fetching current Latitude and Longitude [duplicate] 【发布时间】:2020-07-01 10:42:24 【问题描述】:

我正在为我的项目获取当前的纬度和经度,起初它运行良好,但现在我正在检索空值。我确实打开了位置并授予了物理设备中位置的权限,但仍然得到空值。 我的代码是

mMap.setMyLocationEnabled(true);
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) 
            // TODO: Consider calling
            //    Activity#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for Activity#requestPermissions for more details.
            return;
        

        Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
        double cLatitude = location.getLatitude();
        double cLongitude = location.getLongitude();
        LatLng currentLocation = new LatLng(cLatitude, cLongitude);
        System.out.println("Current Location : "+cLatitude+", "+cLongitude);
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(cLatitude, cLongitude), 13f));

我得到的错误是

java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference

【问题讨论】:

Fetch 使用 FusedLocation Api。 这能回答你的问题吗? How to get current location in Android 【参考方案1】:

添加 LocationListener 以获取当前位置。

private void getLocation() 
      // Get the location manager
      LocationManager locationManager = (LocationManager) 
          getSystemService(LOCATION_SERVICE);
      Criteria criteria = new Criteria();
      String bestProvider = locationManager.getBestProvider(criteria, false);
      Location location = locationManager.getLastKnownLocation(bestProvider);
      LocationListener loc_listener = new LocationListener() 

        public void onLocationChanged(Location l) 

        public void onProviderEnabled(String p) 

        public void onProviderDisabled(String p) 

        public void onStatusChanged(String p, int status, Bundle extras) 
      ;
      locationManager
          .requestLocationUpdates(bestProvider, 0, 0, loc_listener);
      location = locationManager.getLastKnownLocation(bestProvider);
      try 
        lat = location.getLatitude();
        lon = location.getLongitude();
       catch (NullPointerException e) 

      
    

【讨论】:

【参考方案2】:

有什么问题?如果没有检索到任何位置,则可以有一个空位置,例如,因为您在建筑物中。

这是一种更可靠的方法来检索位置

LocationManager mLocationManager;
Location myLocation = getLastKnownLocation();

private Location getLastKnownLocation() 
    mLocationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);
    List<String> providers = mLocationManager.getProviders(true);
    Location bestLocation = null;
    for (String provider : providers) 
        Location l = mLocationManager.getLastKnownLocation(provider);
        if (l == null) 
            continue;
        
        if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) 
            // Found best last known location: %s", l);
            bestLocation = l;
        
    
    return bestLocation;

注意建议使用fused location provider:https://developer.android.com/training/location/retrieve-current

【讨论】:

以上是关于在获取当前纬度和经度时获取空对象引用 [重复]的主要内容,如果未能解决你的问题,请参考以下文章

使用当前位置时,我不断获取位置空值

使用纬度和经度获取特定地址[重复]

从谷歌地图获取经度和纬度的不断更新[重复]

在位置经度和纬度中获取空值

在地图中显示当前位置时获取纬度和经度0.0

如果应用程序在后台运行,如何获取当前位置的纬度和经度?