androidandroid-fragmentskotlinplaceautocompletefragment

PlaceAutocompleteFragment - null cannot be cast to non-null type (Kotlin)


I'm trying to add a Place Autocomplete Fragment into my fragment by following the official documentation here

I get the error kotlin.TypeCastException: null cannot be cast to non-null type com.google.android.gms.location.places.ui.PlaceAutocompleteFragment

I get that PlaceAutocompleteFragment can't be set to null, so i've tried added an if statement in my getAutoCompleteSearchResults() to check if fragmentManager != null, but no luck still

AddLocationFragment.kt

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    getAutoCompleteSearchResults()
}

private fun getAutoCompleteSearchResults() {
        val autocompleteFragment =
            fragmentManager?.findFragmentById(R.id.place_autocomplete_fragment2) as PlaceAutocompleteFragment
        autocompleteFragment.setOnPlaceSelectedListener(object : PlaceSelectionListener {
            override fun onPlaceSelected(place: Place) {
                // TODO: Get info about the selected place.
                Log.i(AddLocationFragment.TAG, "Place: " + place.name)
            }

            override fun onError(status: Status) {
                Log.i(AddLocationFragment.TAG, "An error occurred: $status")
            }
        })
    }
}

XML for the fragment:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/darker_gray"
        tools:context=".AddLocationFragment" tools:layout_editor_absoluteY="81dp">
    <fragment
            android:id="@+id/place_autocomplete_fragment2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
            android:theme="@style/AppTheme"
            app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/etAddress"
            app:layout_constraintEnd_toEndOf="parent"/>

</android.support.constraint.ConstraintLayout>

Solution

  • i figured it out. Since i'm trying to find a fragment within a fragment, i have to do the following:

    val autocompleteFragment =
            activity!!.fragmentManager.findFragmentById(R.id.place_autocomplete_fragment2) as PlaceAutocompleteFragment
    

    We need to get the parent activity