I have an app that fetch data from an api and after that save it to a RoomDatabase(RoomTable).
I display this data with recyclerview in my main screen .
As I said my products are in a model room Table in the database (RoomTable is the name of this table ) , so How can I insert my product to another table in the roomdatabase in this case (CartTAble) after the add button of each product is clicked ?
I hope could've described clearly this . thank's to you .
Tables :
@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)
I also have repository and viewmodel but ignore for simplicity .
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
}
First, your naming convention is wrong. RoomTable and CartTable are note Tables, they are Models or Entitys.
Second. Just create a CartTable with the data from RoomTable.
val modelCart = CartTable(title = products.title)
You can also simply insert only 1 model too. Simply add.
@Insert(replace strategy)
fun insertCart(model: CartTable)
Then just save it into the DB.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.