2014-02-09 54 views
0

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

我真的不知道發生了什麼,因爲它工作良好,並仍然在示例項目中工作得很好。

謝謝。

+0

你如何將「SupportMapFragment」添加到活動中? – CommonsWare

+0

嘗試項目 - >清潔。如果你在XML文件中移動了東西,這通常可以解決問題。 –

+0

@CommonsWare謝謝,我更新了我的帖子。我也清理了這個項目,關閉了eclipse並重新打開它,但仍然不能正常工作 – Copernic

回答

2

那麼,你應該崩潰與ClassCastException。你的佈局有com.google.android.gms.maps.MapFragment,你試圖將其轉換爲SupportMapFragment,這是行不通的。如果這是一個FragmentActivity,則需要在佈局以及Java代碼中使用SupportMapFragment

+0

哇!你是絕對正確的 !我甚至沒有注意到...非常感謝你! – Copernic