我正在使用谷歌地图的片段(导航抽屉(。当应用程序启动时,第一个片段会显示在谷歌地图上。我已经在onViewCreated方法中初始化了谷歌地图。第一次它显示谷歌地图与我的位置完美匹配,但是当我选择另一个片段并返回该片段时,它会抛出空指针异常。
代码中在此处抛出异常:
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
方法:
private void moveCamera(LatLng latLng, float zoom, String title) {
Log.d(TAG, "moveCamera: moving the camera to: " + latLng.latitude + " lon " + latLng.longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}
OnView创建方法:
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
getLocation();
mapView = view.findViewById(R.id.map);
mapView.onCreate(savedInstanceState);
mapView.onResume();
mapView.getMapAsync(this);
}
OnMapReady方法:
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMyLocationEnabled(true);
init();
}
private void getLocation() {
Log.d(TAG, "getDeviceLocation: getting the current device's location");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext());
try {
if (mLocationGranted) {
Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()) {
Log.d(TAG, "device location found");
currentLocation = (Location) task.getResult();
moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()), DEFAULT_ZOOM, "My Location");
} else {
Log.d(TAG, "onComplete: current location is null");
Toast.makeText(getContext(), "unable to get current location", Toast.LENGTH_SHORT).show();
getLocationPermissions();
}
}
});
}
} catch (SecurityException e) {
Log.e(TAG, "SecurityException : " + e.getMessage());
}
}
错误
Exception: java.lang.NullPointerException: Attempt to invoke virtual method
void com.google.android.gms.maps.GoogleMap.moveCamera(com.google.android.gms.map.CameraUpdate)
on a null object reference`
您收到一个 NullPointerException,因为当您尝试移动其相机时,您的地图尚未准备就绪。
您可以尝试执行以下操作
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMyLocationEnabled(true);
init();
getLocation();
}
通过这样做,您的代码将仅在地图可用时尝试移动地图相机,或者更改代码逻辑并从getLocation()
方法中删除您的moveCamere()
,例如将其放入onResume()