PlaceAutocompleteFragment-无法将null强制转换为非null类型(Kotlin)

时间:2019-01-18 06:55:21

标签: android android-fragments kotlin placeautocompletefragment

我正在尝试通过遵循官方文档here

在自己的片段中添加一个位置自动完成片段

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

我知道PlaceAutocompleteFragment不能设置为null,所以我尝试在getAutoCompleteSearchResults()中添加if语句来检查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>

2 个答案:

答案 0 :(得分:0)

实际上是这里错误:

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对象变为可空

答案 1 :(得分:-1)

我想通了。由于我试图在一个片段中查找一个片段,因此我必须执行以下操作:

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

我们需要获取父级活动