Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/232.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 获取当前纬度和经度时获取nul对象引用_Java_Android_Google Maps_Location - Fatal编程技术网

Java 获取当前纬度和经度时获取nul对象引用

Java 获取当前纬度和经度时获取nul对象引用,java,android,google-maps,location,Java,Android,Google Maps,Location,我正在为我的项目获取当前的纬度和经度,起初它工作得很好,但现在我正在检索空值。我确实打开了位置,并在物理设备中为该位置授予了权限,但仍然获得空值。 我的代码是 mMap.setMyLocationEnabled(true); LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new C

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

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

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

这里有一种更健壮的方法来检索位置

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;
}
LocationManager mLocationManager;
位置myLocation=getLastKnownLocation();
私有位置getLastKnownLocation(){
mlLocationManager=(LocationManager)getApplicationContext().getSystemService(位置服务);
List providers=mLocationManager.getProviders(true);
位置bestLocation=null;
for(字符串提供程序:提供程序){
位置l=mLocationManager.getLastKnownLocation(提供者);
if(l==null){
继续;
}
if(bestLocation==null | | l.getAccuracy()

请注意,建议使用
融合位置提供程序

添加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) {

      }
    }

Fetch使用FusedLocation Api。这是否回答了您的问题?