Home > Net >  Firebase(with Kotlin) ArrayList Casting Error
Firebase(with Kotlin) ArrayList Casting Error

Time:08-24

I'm developing a basic shopping app with Kotlin. And I'm using Firebase to upload and retrieve "bought products" ArrayList. I'm uploading it like this:

 val productId = productList.get(position).id
 boughtProductArray.add(productId)
 document.update("boughtItems",boughtProductArray)

And retrieving like this:

        db.collection("gamevalues").document(userId).addSnapshotListener{snapshot, error->
        if(error!=null){
            Toast.makeText(holder.itemView.context,error.localizedMessage,Toast.LENGTH_LONG).show()
        }else{
            if(snapshot!=null && snapshot.exists()){
                boughtProductArray = snapshot.get("boughtItems") as ArrayList<Int>
                for (i in boughtProductArray){
                    println(i)
                }

            }
            else{
                println("Error")
            }

        }

    }

But when I do this, app instantly crashes and gives an error:

2022-08-23 23:02:09.580 19808-19808/com.mycompany.shoppingapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mycompany.shoppingapp, PID: 19808
java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer

And it points this line:

for (i in boughtProductArray){

This is my database structure

CodePudding user response:

The numbers in your boughtItems array are of type Long, and not Int. Since between these two classes, there is no inheritance relationship, the casting is not possible, hence that error. To solve this, please change the of the list from Int to Long:

boughtProductArray = snapshot.get("boughtItems") as ArrayList<Long>
//                                                                        
  • Related