mapFragment.getMapAsync(this) - NullPointerException [英] mapFragment.getMapAsync(this) - NullPointerException

查看:22
本文介绍了mapFragment.getMapAsync(this) - NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 com.google.android.gms:play-services-maps:7.5.0 版本的 Google 地图服务.当试图调用下面我得到 java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' 在空对象引用上.

I am using com.google.android.gms:play-services-maps:7.5.0 version of Google Maps services. When trying to call the below I get 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.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    SupportMapFragment mapFragment = (SupportMapFragment) getActivity().getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this); //error

    return inflater.inflate(R.layout.fragment_example_map, container, false);
}

fragment_example_map.xml 文件:

fragment_example_map.xml file:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="app.ExampleMap">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</FrameLayout>

推荐答案

您正试图在片段存在之前找到它.您指出具有片段的布局是 fragment_example_map.xml.但是,您正在尝试在扩充该布局文件之前找到地图片段.这行不通.

You are attempting to find a fragment before it exists. You indicate that the layout that has the fragment is fragment_example_map.xml. However, you are trying to find the map fragment before you inflate that layout file. This will not work.

除此之外,您似乎试图从另一个片段内部获取地图片段,该片段的 onCreateView() 方法.我不知道你为什么在这里嵌套片段,因为它似乎会让你的代码更复杂和更脆弱,没有明显的好处.

Beyond that, you appear to be trying to get at the map fragment from inside another fragment, in that fragment's onCreateView() method. I do not know why you are nesting fragments here, as it seems like it will make your code more complex and more fragile for no obvious benefit.

这篇关于mapFragment.getMapAsync(this) - NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆