I'll give you some hint of my app , maybe help with my issue .
I have an Api an with retrofit I'll get this data . after that insert all data in roomdatabase .
In my main screen with a recyclerview I display all this product (data) .
Near each of this product I have a button to send product to the cart fragment .also have a value(textview) to save each button is pressed to show how many items gone to cart fragment .
I use a upsert(transaction) for insert or update the product to cart fragment .
and after that use a obvserver livedata to display the amount value of products that is send to cart .
First i need A way to implement the observe live data in my main screen instead of adapter / and also is my upsert query is correct ? sometimes when click on products button the other products value changes .
Here is my code :
Dao :
// this is for Maintable
@Query("SELECT * FROM main")
fun getalldata(): LiveData<List<Roomtable>>
// cart Table
@Query("SELECT * FROM Cart")
fun getAllFromCart(): LiveData<List<CartTable>>
@Query("SELECT * FROM Cart WHERE id = :int")
fun GetAllFromCart(int: Int): LiveData<List<CartTable>>
@Insert(onConflict = OnConflictStrategy.IGNORE)
fun insertToCart(model: CartTable): Long
@Query("UPDATE cart SET amount = amount+1 WHERE id = :int")
fun updateCart(int: Int)
@Transaction
fun upsert(model: CartTable) {
val id = insertToCart(model)
if (id == -1L) {
model.id?.let {
updateCart(it)
}
MainAdapter :
class RecyclerAdapterMain(
private val product: List<Roomtable>,
val context: Context,
private val viewlifecyclerOwner: LifecycleOwner
) :
RecyclerView.Adapter<RecyclerAdapterMain.ViewHolder>() {
val viewModel: ViewModelRoom by lazy {
ViewModelProvider.AndroidViewModelFactory(Application()).create(ViewModelRoom::class.java)
}
inner class ViewHolder(itemview: View) :
RecyclerView.ViewHolder(itemview) {
val title: TextView = itemview.product_txt
val price: TextView = itemview.price_product
val imageproduct: ImageView = itemview.product_image
val btn_add_product: Button = itemview.btn_add_product
var amount_value: TextView = itemview.amount_value
}
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 = product.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
var products = product[position]
holder.title.text = products.title
holder.price.text = products.price
Picasso.get().load(products.image).into(holder.imageproduct)
holder.btn_add_product.setOnClickListener {
products.amount++
viewModel.upsert(
CartTable(
holder.adapterPosition,
products.title,
products.price,
products.image,
products.amount
)
)
viewModel.GetallFromCart(holder.adapterPosition).observe(viewlifecyclerOwner, Observer {
if (it != null) {
for (item in it) {
holder.amount_value.text = item.amount.toString()
}
}
})
}
Main Activity :
class HomeActivity : AppCompatActivity(){
val viewModel: ViewModelRoom by lazy {
ViewModelProvider(this).get(ViewModelRoom::class.java)
}
@RequiresApi(Build.VERSION_CODES.M)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.home_activity)
loadProduct()
@RequiresApi(Build.VERSION_CODES.M)
private fun loadProduct() {
swipeRefreshMain.isRefreshing = true
if (hasNetworkAvilable(applicationContext)) {
viewModel.setup()
viewModel.products.observe(this, Observer {
loadrecycler(it)
})
} else {
Toast.makeText(
applicationContext,
"برای بروز رسانی محصولات اینترنت خود را روشن کنید",
Toast.LENGTH_LONG
).show()
viewModel.getalldata().observe(this, Observer {
if (!it.isNullOrEmpty()) {
loadrecycler(it)
} else {
val builder = AlertDialog.Builder(this)
.setView(R.layout.customalertdialog)
.setPositiveButton("Ok", null)
.create()
.show()
val constraint = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val workmanager: WorkManager = WorkManager.getInstance(this)
val workRequest = OneTimeWorkRequest.Builder(UploadWorkerClass::class.java)
.setConstraints(constraint)
.build()
workmanager.enqueue(workRequest)
}
})
}
}
fun loadrecycler(product: List<Roomtable>) {
val swipeRefreshLayout: SwipeRefreshLayout = findViewById(R.id.swipeRefreshMain)
val recycler: RecyclerView = findViewById(R.id.recycler_main)
recycler.apply {
layoutManager = GridLayoutManager(this@HomeActivity, 2)
adapter = RecyclerAdapterMain(
product, this@HomeActivity, this@HomeActivity )
Handler(Looper.getMainLooper()).postDelayed({
swipeRefreshLayout.isRefreshing = false
}, randomInRange(1, 3) * 1000.toLong())
}
}
}