gpt4 book ai didi

android - PlaceAutocompleteFragment - 不能将 null 转换为非 null 类型 (Kotlin)

转载 作者:行者123 更新时间:2023-12-05 06:28:36 25 4
gpt4 key购买 nike

我正在按照官方文档 here 尝试将一个 Place Autocomplete fragment 添加到我的 fragment 中

我收到错误 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")
}
})
}
}

fragment 的 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

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

解决方案:

使您的转换可空,这样转换就永远不会失败,但会提供空对象,如下所示。

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

现在,您的 autocompleteFragment 对象变为可空

关于android - PlaceAutocompleteFragment - 不能将 null 转换为非 null 类型 (Kotlin),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54249056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com