Java null pointer exception on google places fragment

我与影子孤独终老i 提交于 2019-12-02 08:42:25

SupportMapFragment is not added in Xml Layout file but you are using it in your java code.

 SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);

in your XML:

<fragment 
    android:id="@+id/place_autocomplete_fragment"
    android:name="com.google.android.gms.location.places.ui.SupportPlaceAutocompleteFragment"                          
    android:layout_width="match_parent"                        
    android:layout_height="wrap_content" 
    />

In code: use it as:

 SupportPlaceAutocompleteFragment autocompleteFragment = (SupportPlaceAutocompleteFragment) getSupportFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);

I solved this by including the autocomplete fragment inside the default google maps layout file and the same java file as before. I have posted the final code below.

activity_maps.xml

<LinearLayout android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android" >

<fragment
    android:id="@+id/place_autocomplete_fragment"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment" />

<fragment
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.srinivas.democomplete.MapsActivity>
</LinearLayout>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!