Android get映射上的空指针异常
我正在实现GoogleMapv2API,并获取当前位置。我使用了与Google示例项目完全相同的代码Android get映射上的空指针异常,android,google-maps,Android,Google Maps,我正在实现GoogleMapv2API,并获取当前位置。我使用了与Google示例项目完全相同的代码 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_map); } @Override protected void onResume() { supe
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_map);
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
setUpLocationClientIfNeeded();
mLocationClient.connect();
}
@Override
public void onPause() {
super.onPause();
if (mLocationClient != null) {
mLocationClient.disconnect();
}
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_AddFragment))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(this);
}
}
}
我的布局:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="@+id/map_AddFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment"
tools:ignore="MissingPrefix" />
</RelativeLayout>
当我从示例项目运行此代码时,它可以工作,但当我将此代码复制到我的项目时,它会在mMap=((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map_AddHTag))行上给我一个Null指针异常
.getMap()代码>
我真的不知道发生了什么,因为它运行良好,在示例项目中仍然运行良好
谢谢。好吧,你应该被一个ClassCastException
搞砸了。您的布局具有com.google.android.gms.maps.MapFragment
,您试图将其转换为SupportMapFragment
,但这将不起作用。如果这是一个FragmentActivity
,您需要在布局中以及Java代码中使用SupportMapFragment
。如何将SupportMapFragment
添加到活动中?请尝试Project->Clean。如果您在XML文件中移动了内容,这通常可以解决问题。@commonware谢谢,我已经更新了我的帖子。我还清理了这个项目,关闭了eclipse并重新打开了它,但仍然没有工作哇!你完全正确!我甚至没有注意到。。。多谢各位!