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

如何在Kotlin中将Firestore引用对象通过Intent传递到其他Activity

实现原理

Firebase Firestore的CollectionReference、DocumentReference等引用类均默认实现了Android Parcelable 接口,可直接通过Intent的Extra字段传递,无需自定义序列化逻辑。

1. MainActivity中传递引用

// 你已定义的Firestore引用
val ref = baseRef.collection("intermediate").document("choicesdocument").collection("choices")

// 构建跳转Intent
val intent = Intent(this, SecondActivity::class.java)
// 存入引用,自定义Extra键即可,这里用FIRESTORE_CHOICES_REF做示例
intent.putExtra("FIRESTORE_CHOICES_REF", ref)
// 执行跳转
startActivity(intent)

2. SecondActivity中取回引用

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    // 取回CollectionReference对象,兼容不同Android版本
    val ref = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        intent.getParcelableExtra("FIRESTORE_CHOICES_REF", CollectionReference::class.java)
    } else {
        @Suppress("DEPRECATION")
        intent.getParcelableExtra<CollectionReference>("FIRESTORE_CHOICES_REF")
    }

    // 拿到ref后即可直接执行Firestore操作
    ref?.get()?.addOnSuccessListener { snapshot ->
        // 处理查询结果
    }
}

注意:Extra的键需要在两个Activity中保持一致,避免取值为空。如果传递的是DocumentReference类型,取值时替换泛型和类型参数为DocumentReference::class.java即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 20:24:03