我尝试在我的应用中实施Google地图。我使用导航抽屉并像这样调用我的片段:
//Main-Class
public void onNavigationDrawerItemSelected(int position) {
Fragment myFramgent = null;
switch (position) {
...
case 2 :
myFramgent = new Fillilaen();
System.out.println("FILLIAEN");
break;
...
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, myFramgent)
.commit();
}
Fillialaen班
public class Fillilaen extends SupportMapFragment implements ... {
private GoogleMap mMap;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.fillialen2, container, false);
return myView;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SupportMapFragment fragment = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.location_map);
fragment.getMapAsync(this); //ERROR COMES HERE
}
public void onMapReady(GoogleMap googleMap) {
//never enter this..
mMap = googleMap;
Marker hamburg = mMap.addMarker(new MarkerOptions().position(HAMBURG).title("Hamburg"));
}
}
我的XML
<fragment
android:id="@+id/location_map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
我收到了NullPointerException,我绝对不知道为什么。我搜索了很多并发现了类似的问题,但没有任何帮助。
Nullpointer异常的开始:
致命的例外:主要 过程:roth.com.test6,PID:13097 java.lang.NullPointerException:尝试在null对象引用上调用接口方法'void com.google.maps.api.android.lib6.e.fl.o()' 在com.google.maps.api.android.lib6.e.y.b(未知来源)....
谢谢!
答案 0 :(得分:2)
您正在尝试将SupportMapFragment嵌套在外部SupportMapFragment中。
如果您的Fragment扩展了SupportMapFragment,则无需对任何布局xml进行扩充,您只需调用this.getMapAsync()
,因为this
指的是SupportMapFragment:
public class MyMapFragment extends SupportMapFragment
implements OnMapReadyCallback {
private GoogleMap mMap;
private Marker marker;
public MyMapFragment () {
}
@Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
//"this" is a SupportMapFragment,
//and "this" implements OnMapReadyCallback
// so you can call this.getMapAsync(this) here:
getMapAsync(this);
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
setUpMap();
}
private void setUpMap() {
mMap.setMyLocationEnabled(true);
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng point) {
//remove previously placed Marker
if (marker != null) {
marker.remove();
}
//place marker where user just clicked
marker = mMap.addMarker(new MarkerOptions().position(point).title("Marker")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));
}
});
}
}