【发布时间】:2020-10-25 12:39:12
【问题描述】:
我有多个存储各种文档的集合,我正在尝试访问特定集合,以便可以从特定文档中检索字段。我正在尝试在onStart 中执行此操作@
John Doe ----> "DocumentId (a23bsz12bvxaQw2)" ----> |name: John Doe, age: 23, occupation: teacher|
我能够用另一种方法检索特定的集合,但这只是因为我能够将集合的名称作为参数传递。我获得特定收藏的唯一方法是硬编码fieldPath。
这是我目前的代码:
override fun onStart() {
super.onStart()
val caseManagerNameOnStart = caseManagerName?.text
val notebookRef = db.collection("$caseManagerNameOnStart")
notebookRef.addSnapshotListener(this, object : EventListener<QuerySnapshot?> {
override fun onEvent(querySnap: QuerySnapshot?, ex: FirebaseFirestoreException?) {
if (ex != null) {
return
}
if (querySnap != null) {
for (documentSnapshot in querySnap) {
val appointment = documentSnapshot.toObject(
Appointment::class.java
)
appointment.setId(documentSnapshot.id)
appointment_text_view_date.text =
"Date: " + documentSnapshot["dateAppointment"].toString()
appointment_text_view_time.text =
"Time: " + documentSnapshot["timeAppointment"].toString()
appointment_text_view_case_manager.text =
"Case Manager: " + documentSnapshot["caseManagerName"].toString()
appointment_text_view_client_name.text =
"Client: " + documentSnapshot["userName"].toString()
appointment_text_view_format.text =
"Format: " + documentSnapshot["formatAppointment"].toString()
}
}
}
})
}
val caseManagerNameOnStart = caseManagerName?.text 似乎是空的,当我调用相关活动时应用程序崩溃。 caseManagerName 应该包含可用于 fieldPath 的名称,但有时可能没有要检索的集合,因此不应为 TextView 设置任何内容。
我的预期输出是这样的:
- 获取指定集合
- 从文档中检索字段
- 在给定的 TextView 中显示这些字段
- 如果没有可用的集合,请防止
onStart使应用崩溃。
这是我在 Firestore 中的数据的图像。 Firestore Data
我非常感谢任何意见。感谢您的宝贵时间。
【问题讨论】:
-
caseManagerName是哪种类型的对象? -
它是一个从 EditText 派生的字符串。
-
嘿,你从哪里得到这个
caseManagerName?.text?正如您所说,您将caseManagerNameOnStart设为空,这是您的应用程序崩溃的唯一原因,因为您在db.collection("$caseManagerNameOnStart")中传递空值。尽管请确保该编辑文本字段中有内容,否则您将继续传递 nil 值并且您的应用程序将崩溃 -
您可以设置一些非空流控制到这个字段调用
if (caseManagerNameOnStart.isEmpty()) return或记录一些警告 -
不要描述您的数据库的外观,而是添加它的屏幕截图。
标签: android kotlin google-cloud-firestore