尝试在我们的应用程序上加载谷歌地图时出现 nullpointerException,如下所示。java 类扩展自 AppCompatActivty
和里面intialiseMap()
我们尝试getMap()
D/Profileactivity: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
这是我们在 placeMarker 方法中得到异常的地方
public void placeMarker(LatLongDetails user_latlongobj2,
final Context contextPlace) {
try {
if (googlemap == null) {
intialiseMap();
animatecamera(user_latlongobj);
}
if (LoginDetails.Address.length() < 1) {
LoginDetails.Address = "Getting your location .....";
}
//googlemap.clear();
marker = new MarkerOptions().position(
new LatLng(user_latlongobj2.user_latitude,
user_latlongobj2.user_longitude)).title(
LoginDetails.Address);
System.out.println("This is the Address" + LoginDetails.Address);
marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker));
if (googlemap != null) {
googlemap.addMarker(marker).showInfoWindow();
}else {
intialiseMap();
googlemap.addMarker(marker).showInfoWindow();
}
System.out.println("PLACING MARKER" + LoginDetails.Address);
if (marker == null || contextPlace == null) {
Intent in =new Intent(this,ProfileActivity1.class);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
}
else
fixmarker(marker, contextPlace);
} catch (Exception e) {
fixmarker(marker, contextPlace);
Log.d("Profileactivity", "" + e);
}
}
这是我们初始化 map 的方式
private void intialiseMap() {
try {
if (dialog == null)
dialog = ProgressDialog.show(ProfileActivity1.this, "",
getString(R.string.getting_location), true, true);
}catch(Exception e) {
Log.e("eybaba",""+e);
}
try {
if (googlemap == null) {
googlemap = ((MapFragment) getFragmentManager()
.findFragmentById(R.id.mapfragment)).getMap();
googlemap.setInfoWindowAdapter(new CustomInfowindow(context));
// check if map is created successfully or not
if (googlemap == null) {
Toast.makeText(getApplicationContext(),
R.string.maps_create_error, Toast.LENGTH_SHORT)
.show();
}
}
} catch (Exception e) {
}
}
最佳答案
根据要求回答总结解决方案和找到它的过程:
1) NullPointerException
和相应的消息表明问题出在该 block 的 else 分支中:
if (googlemap != null) {
googlemap.addMarker(marker).showInfoWindow();
}else {
intialiseMap();
googlemap.addMarker(marker).showInfoWindow();
}
这里,intialiseMap();
似乎无法初始化 map 。
2) 在 intialiseMap()
中有一个 try-catch-block,其中 googlemap
如果为 null 则应进行初始化。但是,catch
block 是空的,因此尝试初始化时的任何异常都会丢失。
future 读者请注意:如果您捕获到异常,您应该始终、始终、始终以某种方式处理它。至少做某事的一种简单方法是记录它。
当然,有些情况下您只想忽略特定异常,但在这种情况下您应该真正知道后果(抛出该异常时会发生什么,为什么抛出它等)并且您始终应该记录您是故意忽略该异常的,例如在您的代码中添加简短注释。
3) 在记录捕获的异常后,OP 意识到 googlemap
的初始化失败,因此能够进一步跟踪问题。
然后他搜索了答案和解决方案,并提出了以下两个线程来帮助他解决问题:
关于java - googleMap 上的 addmarker 和 markeroptions 的空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40651945/