You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin开发购物App时Firebase ArrayList类型转换崩溃问题求助

Kotlin购物App Firebase ArrayList类型转换崩溃问题

问题场景与代码

我用Kotlin开发基础购物App,通过Firebase实现「已购商品」ArrayList的上传与获取功能:

上传代码

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

获取代码

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")
        }

    }

}

崩溃错误信息

运行时App直接崩溃,抛出异常:

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

错误指向代码中的for (i in boughtProductArray)行。

数据库结构:boughtItems为数组字段,存储的元素是长整型(Long)数值。

问题原因

Firebase在存储整数类型数据时,默认会将其保存为Long类型,但代码中强制将获取到的数组转换为ArrayList<Int>,遍历过程中Long无法直接转为Int,触发类型转换异常。

解决方案

方案1:手动转换类型

修改获取代码,先将数组转为ArrayList<Long>,再逐个转换为Int:

if(snapshot!=null && snapshot.exists()){
    // 先获取Long类型的数组
    val boughtLongList = snapshot.get("boughtItems") as ArrayList<Long>
    // 转换为Int类型列表
    boughtProductArray = boughtLongList.map { it.toInt() } as ArrayList<Int>
    for (i in boughtProductArray){
        println(i)
    }
}

方案2:使用自定义数据类配合Firebase序列化

这种方式更规范,避免手动类型转换:

  1. 定义对应的数据类:
data class UserPurchase(
    val boughtItems: List<Int>? = null
)
  1. 修改获取代码:
if(snapshot!=null && snapshot.exists()){
    val userPurchase = snapshot.toObject(UserPurchase::class.java)
    userPurchase?.boughtItems?.let {
        boughtProductArray = it as ArrayList<Int>
        for (i in boughtProductArray){
            println(i)
        }
    }
}

Firebase的序列化机制会自动处理Long到Int的转换(只要数值在Int的取值范围内)。

注意事项

上传时productId即使是Int类型,Firebase也会自动转为Long存储,这是正常行为,无需修改上传代码,只需在获取阶段处理类型转换即可。

内容的提问来源于stack exchange,提问作者user17121955

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 17:18:18