I am making an food ordering app where the food item added to the cart from the menu is stored in cloud and is then retrieved by the cart fragment but the code seems fine but item does not show up in cart fragment. When running the application, I am sharing the cart Fragment, cart Adapter,
cart Item and menu item data class. Any help will be appreciated. I am following a tutorial.
Cart Fragment class
package com.example.wavesoffood.Fragment
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.wavesoffood.Model.CartItems
import com.example.wavesoffood.PayOutActivity
import com.example.wavesoffood.R
import com.example.wavesoffood.adapter.CartAdapter
import com.example.wavesoffood.databinding.CartItemBinding
import com.example.wavesoffood.databinding.FragmentCartBinding
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
class CartFragment : Fragment() {
private lateinit var binding: FragmentCartBinding
private lateinit var auth: FirebaseAuth
private lateinit var database: FirebaseDatabase
private lateinit var foodNames: MutableList<String>
private lateinit var foodPrices: MutableList<String>
private lateinit var foodDescriptions: MutableList<String>
private lateinit var foodImageUrl: MutableList<String>
private lateinit var foodIngredients: MutableList<String>
private lateinit var quantity: MutableList<Int>
private lateinit var cartAdapter: CartAdapter
private lateinit var userId: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentCartBinding.inflate(inflater, container, false)
auth = FirebaseAuth.getInstance()
reteriveCartItems()
binding.proccedButton.setOnClickListener {
val intent = Intent(requireContext(), PayOutActivity::class.java)
startActivity(intent)
}
return binding.root
}
private fun reteriveCartItems() {
// database reference to the FireBase
database = FirebaseDatabase.getInstance()
userId = auth.currentUser?.uid ?:""
val foodReference: DatabaseReference =
database.reference.child("user").child(userId).child("CartItems")
//list to Store cart items
foodNames = mutableListOf()
foodPrices = mutableListOf()
foodDescriptions = mutableListOf()
foodImageUrl = mutableListOf()
foodIngredients = mutableListOf()
quantity = mutableListOf()
// fetch data from the database
foodReference.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
for (foodSnapshot in snapshot.children) {
//get the cartItems object from the child node
val cartItems = foodSnapshot.getValue(CartItems::class.java)
// add cart items details to the list
cartItems?.foodName?.let { foodNames.add(it) }
cartItems?.foodPrice?.let { foodPrices.add(it) }
cartItems?.foodDescription?.let { foodDescriptions.add(it) }
cartItems?.foodImage?.let { foodImageUrl.add(it) }
cartItems?.foodQuantity?.let { quantity.add(it) }
cartItems?.foodIngredient?.let { foodIngredients.add(it) }
}
// Set adapter after data is fetched
setAdapter()
}
override fun onCancelled(error: DatabaseError) {
Toast.makeText(context, "Data not fetch", Toast.LENGTH_SHORT).show()
}
})
}
private fun setAdapter() {
cartAdapter = CartAdapter(
requireContext(),
foodNames,
foodPrices,
foodDescriptions,
foodImageUrl,
quantity,
foodIngredients
)
binding.cartRecycleView.layoutManager =
LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
binding.cartRecycleView.adapter = cartAdapter
}
companion object {
}
}
cart Adapter class
package com.example.wavesoffood.adapter
import android.content.Context
import android.net.Uri
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.wavesoffood.databinding.CartItemBinding
import com.example.wavesoffood.databinding.PopularItemBinding
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
class CartAdapter(
private val context: Context,
private val cartItems: MutableList<String>,
private val cartItemPrices: MutableList<String>,
private var cartDescriptions: MutableList<String>,
private var cartImages: MutableList<String>,
private val cartQuantity: MutableList<Int>,
private val cartIngredients: MutableList<String>
) : RecyclerView.Adapter<CartAdapter.CartViewHolder>() {
// get instance of FireBaseauth
private val auth = FirebaseAuth.getInstance()
init {
// instance Firebase
val database = FirebaseDatabase.getInstance()
val userId = auth.currentUser?.uid ?: ""
val cartItemNumber = cartItems.size
ItemQuantities = IntArray(cartItemNumber) { 1 }
cartItemReference = database.reference.child("user").child(userId).child("CartItems")
}
companion object {
private var ItemQuantities: IntArray = intArrayOf()
private lateinit var cartItemReference: DatabaseReference
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CartViewHolder {
val binding = CartItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return CartViewHolder(binding)
}
override fun onBindViewHolder(holder: CartViewHolder, position: Int) {
holder.bind(position)
}
override fun getItemCount(): Int = cartItems.size
inner class CartViewHolder(private val binding: CartItemBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(position: Int) {
binding.apply {
val quantity = ItemQuantities[position]
CartFoodName.text = cartItems[position]
CartPrice.text = cartItemPrices[position]
CartItemQuantity.text = quantity.toString()
//Using glide
val uriString = cartImages[position]
Log.d("image", "food Url: $uriString")
val uri = Uri.parse(uriString)
Glide.with(context).load(uri).into(CartImageFrag)
MinusButton.setOnClickListener {
decreaseQuantity(position)
}
PlusButton.setOnClickListener {
increaseQuantity(position)
}
DeleteButton.setOnClickListener {
val itemPosition = adapterPosition
if (itemPosition != RecyclerView.NO_POSITION) {
deleteItem(itemPosition)
}
}
}
}
private fun increaseQuantity(position: Int) {
if (ItemQuantities[position] < 10) {
ItemQuantities[position]++
binding.CartItemQuantity.text = ItemQuantities[position].toString()
}
}
private fun decreaseQuantity(position: Int) {
if (ItemQuantities[position] > 1) {
ItemQuantities[position]--
binding.CartItemQuantity.text = ItemQuantities[position].toString()
}
}
private fun deleteItem(position: Int) {
val positionRetrieve = position
getUniqueKeyAtPosition(positionRetrieve) { uniqueKey ->
if (uniqueKey != null) {
removeItem(position, uniqueKey)
}
}
}
private fun removeItem(position: Int, uniqueKey: String) {
if (uniqueKey != null) {
cartItemReference.child(uniqueKey).removeValue().addOnSuccessListener {
cartItems.removeAt(position)
cartImages.removeAt(position)
cartDescriptions.removeAt(position)
cartQuantity.removeAt(position)
cartItemPrices.removeAt(position)
cartIngredients.removeAt(position)
Toast.makeText(context, "Item Delete", Toast.LENGTH_SHORT).show()
// update itemQuantities
ItemQuantities =
ItemQuantities.filterIndexed { index, i -> index != position }.toIntArray()
notifyItemRemoved(position)
notifyItemRangeChanged(position, cartItems.size)
}.addOnFailureListener {
Toast.makeText(context, "Failed to Delete", Toast.LENGTH_SHORT).show()
}
}
}
private fun getUniqueKeyAtPosition(positionRetrieve: Int, onComplete: (String?) -> Unit) {
cartItemReference.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
var uniqueKey: String? = null
// loop for snapshot children
snapshot.children.forEachIndexed { index, dataSnapshot ->
if (index == positionRetrieve) {
uniqueKey = dataSnapshot.key
return@forEachIndexed
}
}
onComplete(uniqueKey)
}
override fun onCancelled(error: DatabaseError) {
}
})
}
}
}
cartItems data class
package com.example.wavesoffood.Model
data class CartItems(
val foodName: String?= null,
val foodPrice: String?= null,
val foodDescription: String? = null,
val foodImage: String? = null,
val foodQuantity: Int? = null,
val foodIngredient: String?= null,
)
MenuItems data class
package com.example.wavesoffood.Model
data class MenuItem(
val foodName:String? = null,
val foodprice:String?=null,
val foodDescription:String?=null,
val foodImage:String?=null,
val foodQuantity: Int? = null,
val foodIngredient:String?=null
)