mapFragment中出现的诡异NullPointerException

/ 0评 / 0

最近在写的一个安卓应用需要调用Google Map API。因为完全没有经验,基本操作就是边看油管CodingWithMitch的视频边抄代码。

问题出现在initMap()这个function中。代码如下:

private void initMap(){
        Toast.makeText(this, "Loading Map...", Toast.LENGTH_SHORT).show();
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.google_map_fragment);
        mapFragment.getMapAsync(this);
}

Toast语句执行正常,但是mapFragment.getMapAsync(this)报NullPointerException的错误。可知问题出现在findFragmentById语句没有完成既定任务。检查xml未发现id不匹配的情况:

<RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_weight="50">
            <fragment xmlns:android="http://schemas.android.com/apk/res/android"
                    xmlns:tools="http://schemas.android.com/tools"
                    android:id="@+id/google_map_fragment"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" />
</RelativeLayout>

在StackOverflow等参考资料站泡了许久,都没有找到解决办法。最初以为是因为我的mapFragment放在了RelativeLayout中导致findbyId无法定位。对此,很多人提到将getSupportFragmentManager()改为getChildFragmentManager()。但我尝试不成功,提示cannot solve。其原因在于我的activity class是extends AppCompatActivity而非extends Fragment,故无
getChildFragmentManager()这个方法,自然cannot solve。

最终问题的解决在于发现xml中的fragment缺少class属性。添加之后问题排除。

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

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注