kotlin 如何使用recyclerview MVVM删除房间数据库中的记录

izj3ouym  于 2023-06-24  发布在  Kotlin
关注(0)|答案(3)|浏览(145)

我需要删除一个项目recyclerview适配器,应通知在房间数据库,请帮助我找到一个解决方案,并提前感谢

class ListAdapter : RecyclerView.Adapter<ListAdapter.MyViewHolder>() {
private lateinit var mitemsViewModel: ItemsViewModel
private var itemsList = emptyList<Item>()
private lateinit var item: Item
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
    return MyViewHolder(
        LayoutInflater.from(parent.context).inflate(R.layout.item_row_layout, parent, false)
    )
}
override fun getItemCount(): Int {
    return itemsList.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
    item = itemsList.get(position)
    //always remember this technique to save the values in val type
    val currentItem = itemsList[position]
    holder.itemView.itemNameTV.text = currentItem.itemName.toString()
    holder.itemView.itemCodeTV.text = currentItem.itemCode.toString()
    holder.itemView.itemCategoryTV.text = currentItem.itemCategory.toString()
    holder.itemView.itemDescriptionTV.text = currentItem.itemDescription.toString()
    holder.itemView.itemSellingPriceTV.text = currentItem.itemSellingPrice.toString()
    holder.itemView.itemStockTV.text = currentItem.itemStock.toString()
    holder.itemView.deleteItem.setOnClickListener {
        val itName = holder.itemView.itemNameTV.text.toString()
        val itCode = holder.itemView.itemCodeTV.text.toString()
        val itCategory = holder.itemView.itemCategoryTV.text.toString()
        val itDescription = holder.itemView.itemDescriptionTV.text.toString()
        val itSellingPrice = holder.itemView.itemSellingPriceTV.text.toString()
        val itStock = holder.itemView.itemStockTV.text.toString()
        val itime = Item(0, itName, itCode, itCategory, itSellingPrice, itStock, itDescription)
        mitemsViewModel.deleteItem(itime)
        //dao.deleteItem(itemsList.get(position))
    }
}
fun setData(item: List<Item>) {
    this.itemsList = item
    notifyDataSetChanged()

}}

帮助我如何在recyclerview适配器中初始化ViewModel。运行我的应用程序后的错误代码

kotlin.UninitializedPropertyAccessException: lateinit property mitemsViewModel has not been initialized
    at com.manju.mobilebilling.ui.items.ListAdapter.onBindViewHolder$lambda-0(ListAdapter.kt:65)
    at com.manju.mobilebilling.ui.items.ListAdapter.$r8$lambda$pJauI4KaymNCF6j043M3H3t3CwQ(ListAdapter.kt)
    at com.manju.mobilebilling.ui.items.ListAdapter$$ExternalSyntheticLambda0.onClick(D8$$SyntheticClass)
    at android.view.View.performClick(View.java:5651)
    at android.view.View$PerformClick.run(View.java:22445)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6138)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:893)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:783)
sz81bmfz

sz81bmfz1#

您应该在父ActivityFragment中初始化ItemsViewModel

private val viewModel by viewModels<ItemsViewModel>()

然后,不是直接将其传递给ListAdapter,而是声明一个自定义的click listener并将其用作参数:

// Add a parameter in the adapter
class ListAdapter(
    private val clickListener: ListClickListener
) : RecyclerView.Adapter<ListAdapter.MyViewHolder>() {

    private var itemsList = emptyList<Item>()
    private lateinit var item: Item

    class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        return MyViewHolder(
            LayoutInflater.from(parent.context).inflate(R.layout.item_row_layout, parent, false)
        )
    }

    override fun getItemCount(): Int {
        return itemsList.size
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        item = itemsList.get(position)
        //always remember this technique to save the values in val type
        val currentItem = itemsList[position]
        holder.itemView.itemNameTV.text = currentItem.itemName.toString()
        holder.itemView.itemCodeTV.text = currentItem.itemCode.toString()
        holder.itemView.itemCategoryTV.text = currentItem.itemCategory.toString()
        holder.itemView.itemDescriptionTV.text = currentItem.itemDescription.toString()
        holder.itemView.itemSellingPriceTV.text = currentItem.itemSellingPrice.toString()
        holder.itemView.itemStockTV.text = currentItem.itemStock.toString()
        holder.itemView.deleteItem.setOnClickListener {
            val itName = holder.itemView.itemNameTV.text.toString()
            val itCode = holder.itemView.itemCodeTV.text.toString()
            val itCategory = holder.itemView.itemCategoryTV.text.toString()
            val itDescription = holder.itemView.itemDescriptionTV.text.toString()
            val itSellingPrice = holder.itemView.itemSellingPriceTV.text.toString()
            val itStock = holder.itemView.itemStockTV.text.toString()
            val itime = Item(0, itName, itCode, itCategory, itSellingPrice, itStock, itDescription)
            // Call the click listener
            clickListener.onClick(iitem)
        }
    }

    fun setData(item: List<Item>) {
        this.itemsList = item
        notifyDataSetChanged()

    }
}

// Click listener class
class ListClickListener(val clickListener: (item: Item) -> Unit) {
    fun onClick(item: Item) = clickListener(item)
}

最后,在父ActivityFragment中声明ListAdapter

val adapter = ListAdapter(ListClickListener { item -> 
    viewModel.deleteItem(item)
})
avwztpqn

avwztpqn2#

在Activity中初始化视图模型,而不是通过适配器构造函数传递它

oymdgrw7

oymdgrw73#

如果您想通过MVVM和ROOM执行此操作,请执行以下步骤:
1.创建你自己的Item类,并在Dao接口下面标识delete和insert方法。
@Dao接口DaoItem {

@Delete
 suspend fun delete(item: Item)
           
@Insert        
 suspend fun insertItem(item: Item)
        }
        
        }

1.创建存储库类:
class RepositoryItem(瓦尔daoItem:(){

suspend fun insertItem(item: Item){
            daoItem.insertItem(item)
        }
    
      suspend fun deleteItem(item: Item) {
             daoItem.delete(item)
            }
        }
    }

1.然后在MVVM类中创建一个delete方法:
public void run(val){

fun deleteValue(item: Item) {
                 viewModelScope.launch {
                     repositoryItem.deleteItem(item:Item)
                 }
             }
         }

在适配器中使用clicklistener访问项目:

class ListAdapter(val clickListener: (Item)->Unit):RecyclerView.Adapter<ListAdapter.MyViewHolder>()
     {

class ViewHolder(item:View ):RecyclerView.ViewHolder(item){
 fun bind(item: Item,clickListener: (Item)->Unit) {

            val itName = itemView.itemNameTV.text.toString()
            val itCode = itemView.itemCodeTV.text.toString()
            val itCategory = itemView.itemCategoryTV.text.toString()
           val itime = Item(0, itName, itCode, itCategory)
   itemView.deleteItem.setOnClickListener(){
                clickListener(itime)

            }

}

在下面的步骤中,你需要在你的act或fragment类中声明mvvm类,并创建下面的方法来通过mvvm删除回收器视图的项目:

fun rowItemClicked(item: Item){
        viewModelItem.deleteValue(item)
        listAdapter.notifyDataSetChanged()
    }

和/或

override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,savedInstanceState: Bundle? ): View? {

        listAdapter = ListAdapter( { item:Item->rowItemClicked(item)})

}

相关问题