java - 避免方法调用 getLatitude 可能会产生 java.Lang.NullPointerException

标签 java android fusedlocationproviderclient

我有一种方法可以在 map 上显示设备的当前位置。我使用 FusedLocationProviderClient 因为它似乎是最准确的。

currentLocation.getLatitude() 上,我收到警告:

Method invocation may produce java.Lang.NullPointerException

如何避免这种风险?为什么它只与 currentLocation.getLatitude() 相关,而不与 currentLocation.getLongitude() 相关?

private void getDeviceLocation(){
    Log.d(TAG, "getDeviceLocation: getting the devices current location");

    FusedLocationProviderClient mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

    try{
        if(mLocationPermissionsGranted){

            final Task location = mFusedLocationProviderClient.getLastLocation();

            location.addOnCompleteListener(task -> {
                if(task.isSuccessful()){
                    Log.d(TAG, "onComplete: found location!");

                    Location currentLocation = (Location) task.getResult();
                    LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());

                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, DEFAULT_ZOOM));

                }else{
                    Log.d(TAG, "onComplete: current location is null");
                }
            });
        }
    }catch (SecurityException e){
        Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage() );
    }
}

最佳答案

IDE 在显示有关代码的信息时可能会很奇怪或被误解,但我向您保证它适用于 getLongitude() 以及实例方法或实例成员的任何其他调用,因为位置可能为 null。

public Task getLastLocation ()
Returns the best most recent location currently available.

If a location is not available, which should happen very rarely, null will be returned. The best accuracy available while respecting the location permissions will be returned.

This method provides a simplified way to get location. It is particularly well suited for applications that do not require an accurate location and that do not want to maintain extra logic for location updates.

https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient.html#getLastLocation()

所以即使任务成功,任务的结果也可能为空。这意味着您需要在使用之前检查 location 是否为空。

关于java - 避免方法调用 getLatitude 可能会产生 java.Lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56158488/

相关文章:

android - Edittext 在 ScrollView 中不可滚动

java - Android RecyclerView示例误解

java - Android Studio 错误 "Private field ' '“已分配但从未访问过

android - 使用 FusedLocationProviderClient、JobScheduler 和 JobService 更新位置

android - 除非首先连接到 WIFI 网络,否则 FusedLocationProviderClient 无法通过 3G 或 4G 网络获取 GPS 位置

java - 移动和旋转碰撞矩形

java - Android中输入新的子节点后如何删除最旧的子节点

java - 使用正则表达式验证项目文件

java - 使用位置回调获取位置更新

java netbeans 命令行参数传递