我正在实现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>
当我从示例项目中运行此代码时,它可以工作,但是当我将此代码复制到我的项目中时,它会在行mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_AddHTag))
.getMap();
上为我Null pointer exception
我真的不知道发生了什么,因为它运行良好,并且在示例项目中仍然运行良好。
谢谢。
好吧,你应该崩溃与ClassCastException
.你的布局有com.google.android.gms.maps.MapFragment
,你试图把它投射到SupportMapFragment
,这是行不通的。如果这是一个FragmentActivity
,则需要在布局以及Java代码中使用SupportMapFragment
。