开发了购物车窗口。数据被写入数据库。当您单击删除图标时,产品将从数据库和用户窗口中删除,但应用程序崩溃并出现错误,将我引导至以下代码:
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 var cartIngredient: MutableList<String>
) : RecyclerView.Adapter<CartAdapter.CartViewHolder>() {
private val auth = FirebaseAuth.getInstance()
init {
val database = FirebaseDatabase.getInstance()
val userId = auth.currentUser?.uid?:""
val cartItemNumber = cartItems.size
itemQuantities = IntArray(cartItemNumber){1}
cartItemsReference = database.reference.child("user").child(userId).child("CartItems")
}
companion object{
private var itemQuantities: IntArray = intArrayOf()
private lateinit var cartItemsReference: 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
fun getUpdatedItemsQuantities(): MutableList<Int> {
val itemQuantity = mutableListOf<Int>()
itemQuantity.addAll(cartQuantity)
return itemQuantity
}
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]
cartItemPrice.text = cartItemPrices[position]
val uriString = cartImages[position]
val uri = Uri.parse(uriString)
Glide.with(context).load(uri).into(cartImage)
cartItemQuantity.text = quantity.toString()
minusbutton.setOnClickListener {
deceaseQuantity(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]++
cartQuantity[position] = itemQuantities[position]
binding.cartItemQuantity.text = itemQuantities[position].toString()
}
}
private fun deceaseQuantity(position: Int) {
if (itemQuantities[position] > 1) {
itemQuantities[position]--
cartQuantity[position] = itemQuantities[position]
binding.cartItemQuantity.text = itemQuantities[position].toString()
}
}
private fun deleteItem(position: Int) {
val positionRetrieve = position
getUniqueAtPosition(positionRetrieve){uniqueKey ->
if (uniqueKey !=null){
removeItem(position, uniqueKey)
}
}
}
private fun removeItem(position: Int, uniqueKey: String) {
if (uniqueKey != null){
cartItemsReference.child(uniqueKey).removeValue().addOnSuccessListener {
cartItems.removeAt(position)
cartImages.removeAt(position)
cartDescriptions.removeAt(position)
cartQuantity.removeAt(position)
cartItemPrices.removeAt(position)
cartIngredient.removeAt(position)
Toast.makeText(context, "Товар удален", Toast.LENGTH_SHORT).show()
itemQuantities = itemQuantities.filterIndexed { index, i -> index!= position }.toIntArray()
notifyItemRemoved(position)
notifyItemRangeChanged(position, cartItems.size)
}.addOnFailureListener {
Toast.makeText(context, "Ошибка при удалении", Toast.LENGTH_SHORT).show()
}
}
}
private fun getUniqueAtPosition(positionRetrieve: Int, onComplete:(String?) -> Unit) {
cartItemsReference.addListenerForSingleValueEvent(object : ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
var uniqueKey: String?= null
snapshot.children.forEachIndexed { index, dataSnapshot ->
if (index == positionRetrieve){
uniqueKey = dataSnapshot.key
return@forEachIndexed
}
}
onComplete(uniqueKey)
}
override fun onCancelled(error: DatabaseError) {
}
})
}
}
}
最初,我认为它是在尝试删除空值,但显然我错了
结果,这个错误一直出现:
FATAL EXCEPTION: main
Process: com.example.burgerexpress, PID: 5911
java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
at jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266)
at java.util.Objects.checkIndex(Objects.java:359)
at java.util.ArrayList.remove(ArrayList.java:511)
at com.example.burgerexpress.adaptar.CartAdapter$CartViewHolder$removeItem$1.invoke(CartAdapter.kt:128)
at com.example.burgerexpress.adaptar.CartAdapter$CartViewHolder$removeItem$1.invoke(CartAdapter.kt:122)
at com.example.burgerexpress.adaptar.CartAdapter$CartViewHolder.removeItem$lambda$4(CartAdapter.kt:122)
at com.example.burgerexpress.adaptar.CartAdapter$CartViewHolder.$r8$lambda$LnXtKbI5zByXyRZrlH1St-Zw9gw(Unknown Source:0)
at com.example.burgerexpress.adaptar.CartAdapter$CartViewHolder$$ExternalSyntheticLambda3.onSuccess(D8$$SyntheticClass:0)
at com.google.android.gms.tasks.zzm.run(com.google.android.gms:play-services-tasks@@18.1.0:1)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:210)
at android.os.Looper.loop(Looper.java:299)
at android.app.ActivityThread.main(ActivityThread.java:8319)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:556)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1038)
2024-05-24 12:09:45.373 5371-5595 DigestGenerator com.miui.daemon D digest=============com.example.burgerexpressjava.lang.IndexOutOfBoundsException: Index out of bounds for length
at jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:XX)
at jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:XX)
at jdk.internal.util.Preconditions.checkIndex(Preconditions.java:XX)
at java.util.Objects.checkIndex(Objects.java:XX)
at java.util.ArrayList.remove(ArrayList.java:XX)
at com.example.burgerexpress.adaptar.CartAdapter$CartViewHolder$removeItem$.invoke(CartAdapter.kt:XX)
at com.example.burgerexpress.adaptar.CartAdapter$CartViewHolder$removeItem$.invoke(CartAdapter.kt:XX)
at com.example.burgerexpress.adaptar.CartAdapter$CartViewHolder.removeItem$lambda$(CartAdapter.kt:XX)
at com.example.burgerexpress.adaptar.CartAdapter$CartViewHolder.$r$lambda$LnXtKbIzByXyRZrlHSt-Zwgw(Unknown Source:)
at com.example.burgerexpress.adaptar.CartAdapter$CartViewHolder$$ExternalSyntheticLambda.onSuccess(XX$$SyntheticClass:)
at com.google.android.gms.tasks.zzm.run(com.google.android.gms:play-services-tasks@XX..:)
at android.os.Handler.handleCallback(Handler.java:XX)
at android.os.Handler.dispatchMessage(Handler.java:XX)
at android.os.Looper.loopOnce(Looper.java:XX)
at android.os.Looper.loop(Looper.java:XX)
at android.app.ActivityThread.main(ActivityThread.java:XX)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:XX)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:XX)
这是大小限制问题,因此,在每个调用的removeAt函数中添加if条件 即
if(cartItems.size() >= position - 1){
cartItems.removeAt(position)
}