在我的应用程序中,我使用的导航抽屉与刷卡选项卡(以下this),并在这些选项卡之一我想要使用谷歌地图。我得到这个错误:谷歌地图v2里面的片段返回void
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
我已经搜查,发现我只能在主线程中调用getMapAsync()
。然而,我面临的几乎所有解决方案都是使用不推荐的方法。我如何初始化地图,以避免null异常,并只在该选项卡上调用它?
我的标签片段
public class PrimaryFragment extends Fragment implements OnMapReadyCallback {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.primary_layout,container,false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SupportMapFragment supportMapFragment = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map));
supportMapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
//toDO
}
}
的标签片段XML
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:id="@+id/map"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>
</FrameLayout>
[Check this SO link](https://stackoverflow.com/a/32004257/2715073)可能适合你。 – Pankaj