首页 > 解决方案 > PlaceAutocompleteFragment - null 不能转换为非 null 类型(Kotlin)

问题描述

我正在尝试按照此处的官方文档将 Place Autocomplete Fragment 添加到我的片段中

我得到错误kotlin.TypeCastException: null cannot be cast to non-null type com.google.android.gms.location.places.ui.PlaceAutocompleteFragment

我知道 PlaceAutocompleteFragment 不能设置为 null,所以我尝试在我的中添加一个 if 语句getAutoCompleteSearchResults()来检查 fragmentManager != null,但仍然没有运气

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:

<?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>

标签: androidandroid-fragmentskotlinplaceautocompletefragment

解决方案


实际上错误在这里:

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

您正在将一个可为的对象转换为非空接收器类型。

解决方案 :

使您的投射可以为,以便投射永远不会失败,但提供如下所示的空对象。

val autocompleteFragment = fragmentManager?.findFragmentById(R.id.place_autocomplete_fragment2) as? PlaceAutocompleteFragment // Make casting of 'as' to nullable cast 'as?'

所以现在,你的autocompleteFragment对象变成了nullable


推荐阅读