android - 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>
解决方案
实际上错误在这里:
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。
推荐阅读
- laravel - 如何从 Laravel 5.8 的视图中将参数传递给 getFooAttribute() megic 方法
- c - 这段代码的输出是什么,你能解释一步一步的进展吗?
- python - 尝试使用 astropy 将 FITS 文件转换为 ndarray 时获取 NaN 值
- java - 运行 gradle clean build 时面临问题
- excel - 如何通过excel vba将值输入网站输入
- ember.js - dayJS 是否有任何“ember-moment-shim”替代方案?
- angular - 从 Angular 应用程序调用第三方 API 时无法传递客户标头选项
- pine-script - 根据条件定义入场价格
- c# - How to convert timezone offset text "+01:00" to timespan
- kotlin - Kotlin MPP - 无法解析 Stetho 拦截器