从文件室数据库kotlin中删除项目

vqlkdk9b  于 2021-07-12  发布在  Java
关注(0)|答案(0)|浏览(292)

我在删除项目时遇到以下错误java.lang.indexoutofboundsexception:索引:0,大小:0。上面说第五行有问题。我想我指的是数组之外的元素,但我不知道如何解决这个问题
删除操作:

private fun deleteSwipeAction() {
    val swipeHandler = object : ItemSimpleTouch(requireContext()) {
        override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
            val position = viewHolder.absoluteAdapterPosition
            val item = viewModel.products?.get(position)
            val name = item?.name
            adapter.deleteItem(position)
            viewModel.deleteProduct(item)

            showActionSnackbar(rv_product_list, "Вы удалили $name", "Востановить",
                { restoreDeletedItem(item, position)}, requireContext())
        }
    }
    val itemTouchHelper = ItemTouchHelper(swipeHandler)
    itemTouchHelper.attachToRecyclerView(rv_product_list)
}

视图模型:

class ProductViewModel : ViewModel() {
private val repository = ProductRepository()

val data: MutableLiveData<MutableList<Product>> = MutableLiveData()
var products: MutableList<Product>? = mutableListOf()

init {
    subscribeToData()
    repository.getProducts()
}

fun insertProduct(data: Product?) {
    if (data != null) {
        repository.insertProduct(data)
    }
}

fun deleteProduct(data: Product?) {
    if (data != null) {
        repository.deleteProduct(data)
    }
}

private fun subscribeToData() {
    repository.data.observeForever {
        data.value = it
        products = data.value
    }
}

}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题