在我将 getMap() 更改为 getMapAsync() 并实现 OnMapReadyCallback 后,我收到错误 NullPointerException。
这里是 logcat
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.setMyLocationEnabled(boolean)' on a null object reference at pym.example.com.fypv2.callme.Callme.onCreate(Callme.java:117)`
这里是代码
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
// Enabling MyLocation in Google Map
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#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 ActivityCompat#requestPermissions for more details.
return;
}
mGoogleMap.setMyLocationEnabled(true);
和 OnMapReady
@Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
}
最佳答案
在 onMapReady
中准备好 map 后,您需要调用 GoogleMap.setMyLocationEnabled(true);
。
如下更改您的代码:
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
@Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#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 ActivityCompat#requestPermissions for more details.
return;
}
mGoogleMap.setMyLocationEnabled(true);
}
关于android - 谷歌地图 getMapAsync() NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43818307/