我正在实施Google Map V2 api并获取当前位置。我已经使用完全相同的代码作为谷歌示例项目,获取地图的空指针例外
@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>
当我运行从它的工作示例项目的代码,但是当我将此代码复制到我的项目,它给了我一个Null pointer exception
就行mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_AddHTag)) .getMap();
我真的不知道发生了什么,因为它工作良好,并仍然在示例项目中工作得很好。
谢谢。
你如何将“SupportMapFragment”添加到活动中? – CommonsWare
尝试项目 - >清洁。如果你在XML文件中移动了东西,这通常可以解决问题。 –
@CommonsWare谢谢,我更新了我的帖子。我也清理了这个项目,关闭了eclipse并重新打开它,但仍然不能正常工作 – Copernic