我正在實施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