【发布时间】:2016-11-17 10:06:21
【问题描述】:
尝试在我们的应用程序上加载谷歌地图时出现 nullpointerException
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);
}
}
这就是我们初始化地图的方式
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) {
}
}
【问题讨论】:
-
我猜
intialiseMap();不起作用或返回新地图,因此调用应该是googlemap = intialiseMap();。基本上错误信息会告诉你出了什么问题:NullPointerException. -
第一个警告显示
user_longitude类LatLongDetails是您通过实例user_latlongobj2.user_longitude访问的类变量,但具有static修饰符。你可以简单地删除static。 -
@Thomas google= intialiseMap();给出不兼容的类型错误
-
else { intialiseMap(); googlemap.addMarker(marker).showInfoWindow(); }googlemap 为null时,这段代码被执行。参考@Thomas 评论,您需要以some 方式对其进行初始化。 -
@QBrute 我在问问题之前添加了这一行,以检查这是否会解决空指针异常
标签: java android google-maps google-maps-markers google-maps-android-api-2