簡體   English   中英

PlaceAutocompleteFragment-無法將null強制轉換為非null類型(Kotlin)

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

我正在嘗試通過遵循此處的官方文檔將位置自動完成片段添加到我的片段中

我收到錯誤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>

實際上錯誤在這里:

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

您正在將空的對象強制轉換為非空的接收器類型。

解決方案:

使您的演員表可以為空,以便演員表永遠不會失敗,但可以提供如下所示的null對象

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

因此,現在,您的autocompleteFragment對象變為可為null

我想到了。 由於我試圖在一個片段中查找一個片段,因此我必須執行以下操作:

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

我們需要進行家長活動

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM