我刚开始学习 Kotlin Android,我决定在我的第一个 Kotlin 应用程序 Coroutines 和 Kodein 库中使用。我的问题是返回房间数据库中创建的对象列表。我知道如何为 Recyclerview 设置简单列表,但是我在通过 Coroutines 设置 Recyclerview 中的对象列表时遇到问题。
来自使用 Recyclerview 的活动的函数:
private fun getCities() = launch(Dispatchers.Main) {
var locationList = addLocationViewModel.location.await()
locationList.observe(this@AddLocationActivity, Observer {
viewAdapter = LocationAdapter(locationList, this)
})
}
如您所见,LocationAdapter 中的第一个参数是 locationList,这个参数带有红色下划线。错误意味着:
Type mismatch.
Required: kotlin.collections.ArrayList<Location>
Found: LiveData<List<Location>>
如何解决这个问题?
Adapter:
class LocationAdapter(
private val cities: ArrayList<Location>,
private val context: Context
) : RecyclerView.Adapter<LocationAdapter.LocationViewHolder>() {
private var removedPosition: Int = 0
private var removedItem: String = ""
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LocationViewHolder {
val layoutInflater = LayoutInflater.from(context)
val contactRow = layoutInflater.inflate(R.layout.location_recyclerview_item, parent, false)
return LocationViewHolder(contactRow)
}
override fun getItemCount(): Int {
return cities.size
}
override fun onBindViewHolder(holder: LocationViewHolder, position: Int) {
val location = holder.view.location_text_view_item
location.text = cities.get(position).toString()
}
class LocationViewHolder(val view: View) : RecyclerView.ViewHolder(view)
fun removeItem(viewHolder: RecyclerView.ViewHolder) {
removedItem = viewHolder.adapterPosition.toString()
removedItem = cities[viewHolder.adapterPosition].toString()
cities.removeAt(viewHolder.adapterPosition)
notifyItemRemoved(viewHolder.adapterPosition)
}
}
视图模型:
class AddLocationViewModel(
private val locationRepository: LocationRepository
) : ViewModel() {
val location by lazyDeferred {
locationRepository.getAllLocations()
}
fun insertLocation(location: Location) {
locationRepository
}
}