如何在android中将数据从一个房间表插入另一个房间



我有一个应用程序,可以从api中提取数据,然后将其保存到RoomDatabase(RoomTable(中。

我在主屏幕上用recyclerview显示这些数据。

正如我所说,我的产品在数据库中的样板间表中(RoomTable是该表的名称(,那么在单击每个产品的添加按钮后,我如何将我的产品插入到room数据库中的另一个表中(CartTAble(?

我希望能清楚地描述这一点。谢谢你。

表格:

@entity
class RoomTable (

@primarykey
autoincrement = true
val id : Int 
val title : String 

@entity
class CartTAble (

@primarykey
autoincrement = true
val id : Int 
val title : String 
)

DAO


@Insert(replace strategy)
fun insertToCart(model : List<CartTable)

我也有存储库和视图模型,但为了简单起见,忽略了它们。

adapter : 
class Myadapter (myproduct : List<RoomTAble> ) : Recycerlview.Adapter<Myadapter.Viewholder>(){
val viewmodel : Viewmodelroom()
class Viewholder (view : View ) : RecyclerView.ViewHolder(){
val title =  view.findviewbyid(R.id.sometihng)
val image = view.finviewbyid(R.id.Someimage)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {

val layoutview =
LayoutInflater.from(parent.context).inflate(R.layout.product_items, parent, false)
return ViewHolder(layoutview)
}

override fun getItemCount(): Int = myproduct.size

override fun onBindViewHolder(holder: ViewHolder, position: Int) {

val products = myproduct[position]

holder.title.text = products.title
Picasso.get().load(products.image).into(holder.imageproduct)

holder.btn_add_product.setOnClickListener {
viewModel.insertToCart()
// in here for insertTocart paramter it need list<CArtTAble> but we have just list of RoomTAble
}

首先,您的命名约定是错误的。RoomTable和CartTable是注释表,它们是模型或实体。

第二。只需使用RoomTable中的数据创建CartTable。

val modelCart = CartTable(title = products.title)

您也可以简单地只插入一个模型。只需添加即可。

@Insert(replace strategy)
fun insertCart(model: CartTable)

然后将其保存到数据库中。

最新更新