Supporting Multiple Product Entries with Distinct Quantities in Android Kotlin Ecommerce

How can I add various items with individual quantities to the cart in a Kotlin Android shopping app? See revised sample code below.

package com.example.shopapp.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.example.shopapp.databinding.FragmentDetailBinding

class DetailScreenFragment : Fragment() {
    private lateinit var binding: FragmentDetailBinding
    var itemCount = 0

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        binding = FragmentDetailBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        binding.plusButton.setOnClickListener {
            itemCount++
            binding.countText.text = itemCount.toString()
        }
        binding.addToCartButton.setOnClickListener {
            // Logic to add product card with itemCount
        }
    }
}
package com.example.shopapp.viewmodel

import androidx.lifecycle.ViewModel

class ShopViewModel : ViewModel() {
    var uniqueQuantity = 0
}

Hey Sky_Dreamer, this is a super interesting problem you’ve got. I was thinking, maybe you could enhance your design by having a separate data model for each cart item. That model could hold both the product info and its specific quantity, which you update as each item is added. Then you make a mutable list of these models in your ViewModel to maintain state. I’m curious, have you considered what might happen if users want to update quantities directly from the cart view? It could be neat to keep the UI and data model in sync. Also, what approach do you plan to take for managing multiple entries: are you okay with having duplicate entries that sum quantities or do you want to merge them by product id? Would be awesome to hear your thoughts and maybe even explore some reactive programming options with LiveData or StateFlow for a more dynamic experience!

In a similar project, I encountered the same challenge and found that centralizing the product handling logic in the ViewModel proved particularly effective. I created a dedicated cart item model containing the product details and quantity for each entry. Instead of relying on separate mutable states for each detail screen, I maintained a collection that was updated by key, thus avoiding issues with duplicate or incorrectly merged entries. This approach ensured that any update to a product’s quantity was immediately reflected in the overall cart, and it made debugging much simpler.