获取地图上的空指针异常

时间:2014-02-09 16:23:02

标签: android google-maps

我正在实施Google Map V2 api,并获取当前位置。我使用了与Google示例项目完全相同的代码,

@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();提供了一个

我真的不知道发生了什么,因为它工作得很好,并且仍然在示例项目中运作良好。

谢谢。

1 个答案:

答案 0 :(得分:1)

好吧,你应该使用ClassCastException崩溃。您的布局有com.google.android.gms.maps.MapFragment,并且您尝试将其转换为SupportMapFragment,这将无效。如果这是FragmentActivity,则需要在布局中使用SupportMapFragment以及使用Java代码。