How to implement multi-item cart functionality in Android Kotlin e-commerce app?

I’m working on an e-commerce app in Android using Kotlin. Right now I can show products on the home screen that I get from an API. Users can view product details and add items to their cart with a specific quantity. But I’m stuck on how to let users add different products with varying quantities to the cart.

The cart should display each product on a separate card. I’ve got it working for one product type, but the quantity is the same for all products when clicked.

Here’s what I’ve tried in my ProductDetailFragment:

class ShopItemFragment : Fragment() {
    private lateinit var binding: FragmentShopItemBinding
    private val shopViewModel: ShopViewModel by activityViewModels()

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.itemDetails = arguments?.getParcelable("item")
        val itemDetail = binding.itemDetails

        binding.addToBasketButton.setOnClickListener {
            shopViewModel.itemCount++
            binding.quantityDisplay.text = shopViewModel.itemCount.toString()
            Toast.makeText(activity, "Added to basket", Toast.LENGTH_SHORT).show()
        }

        binding.checkoutButton.setOnClickListener {
            val bundle = Bundle()
            bundle.putString("item_count", shopViewModel.itemCount.toString())
            val basketFragment = BasketFragment()
            basketFragment.arguments = bundle

            parentFragmentManager.beginTransaction()
                .replace(R.id.fragmentContainer, basketFragment)
                .addToBackStack(null)
                .commit()
        }
    }
}

Any ideas on how to handle multiple product types and quantities in the cart?

I’ve tackled a similar challenge in my e-commerce app. Instead of using a single itemCount, consider implementing a CartItem data class to represent each product in the cart. You could structure it like this:

data class CartItem(val id: Int, val name: String, var quantity: Int, val price: Double)

Then, in your ViewModel, maintain a list of CartItems:

val cartItems = mutableListOf<CartItem>()

fun addToCart(product: Product, quantity: Int) {
    val existingItem = cartItems.find { it.id == product.id }
    if (existingItem != null) {
        existingItem.quantity += quantity
    } else {
        cartItems.add(CartItem(product.id, product.name, quantity, product.price))
    }
}

This approach allows you to manage multiple products with different quantities. For displaying the cart, use a RecyclerView with a custom adapter to show each CartItem. This method has worked well in my projects, providing flexibility and scalability for cart management.

hey man, i kno the struggle! i had similar issues with my app. try using a list to store cart items. each item could have product ID, name, quantity, and price. then update quantities for specific products instead of one global count.

in ur viewmodel, u could do something like:

val cartItems = mutableListOf<CartItem>()

fun addToCart(product: Product, qty: Int) {
    val existingItem = cartItems.find { it.id == product.id }
    if (existingItem != null) {
        existingItem.quantity += qty
    } else {
        cartItems.add(CartItem(product.id, product.name, qty, product.price))
    }
}

hope this helps! lemme kno if u need more info

Hey there! I’ve been working on a similar e-commerce app and ran into the same issue. Have you thought about using a List or HashMap to store your cart items? That way, you can keep track of different products and their quantities separately.

For example, you could create a CartItem data class with productId, name, quantity, and price. Then in your ViewModel, you could have something like:

val cartItems = mutableListOf<CartItem>()

fun addToCart(product: Product, quantity: Int) {
    val existingItem = cartItems.find { it.productId == product.id }
    if (existingItem != null) {
        existingItem.quantity += quantity
    } else {
        cartItems.add(CartItem(product.id, product.name, quantity, product.price))
    }
}

This way, each product in the cart has its own quantity. You could then use a RecyclerView in your cart fragment to display all the items.

Have you tried something like this? What other approaches have you considered for managing multiple products in the cart?