0

我刚开始学习 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
}
}
4

2 回答 2

2

错误本身不言自明,您的 VM 正在返回类型的对象LiveData<List<Location>>

而不是将 locationList(它是 livedata)对象直接传递给适配器,而是像下面这样创建 lambda

private fun getCities() = launch(Dispatchers.Main) {
    var locationList = addLocationViewModel.location.await()
    locationList.observe(this@AddLocationActivity, Observer { 
        locList -> viewAdapter = LocationAdapter(locList, this)
    })
}
于 2019-07-26T12:40:28.827 回答
0

只需获取 LiveData 对象的值,如下所示:

viewAdapter = LocationAdapter(locationList.value!!, this)
于 2019-07-27T11:22:03.387 回答