这个问题我已经困扰了一段时间了。我有 3 个 inputEditText,要求用户输入他们的名字、姓氏和 ID。我想将此信息保存到 google firestore 中。我已经设置了所有依赖项,并且我知道我已将其正确连接到 google firebase。我发现的问题是,关于这个主题的每个教程都彼此不同,而且我能找到的每个教程都不能 100% 发挥作用。有没有办法将这 3 个值保存到 kotlin 中的 google firestore 中,并在另一个 Activity 中检索这些值?
最佳答案
I've been having this issue for a while. I have 3 inputEditTexts that ask the user to input their first name, last name, and their ID.
要从这些 EditText 对象获取数据,请使用以下代码行:
val firstName = firstNameEditText.text.toString().trim()
val lastName = lastNameEditText.text.toString().trim()
val id = idEditText.text.toString().trim()
I wanted to save this information into Firestore.
要将数据保存在 Firestore 中,最简单的解决方案是创建一个数据类:
data class User(
var firstName: String? = null,
var lastName: String? = null,
var id: String? = null
)
创建该类的对象:
val user = User(firstName, lastName, id)
并将其写入 Firestore:
val rootRef = FirebaseFirestore.getInstance()
val usersRef = rootRef.collection("users")
usersRef.document(id).set(user).addOnCompleteListener(/* ... */)
这将产生以下数据库架构:
Firestore-root
|
--- users (collection)
|
--- $id
|
--- firstName: "Abrahim"
|
--- lastName: "Mahmud"
|
--- id: "userIdIntroducedFromKeyboard"
要读回数据,只需调用 get() 并附加一个监听器,如下所示:
val uidRef = usersRef.document(id)
uidRef.get().addOnSuccessListener { doc ->
if (doc != null) {
val user = doc.toObject(User::class.java)
Log.d(TAG, "{$user.firstName} {$user.lastName}")
} else {
Log.d(TAG, "No such document")
}
}.addOnFailureListener { exception ->
Log.d(TAG, "get failed with ", exception)
}
logcat 中的结果将是:
Abrahim Mahmud
关于android - Google Firestore 保存用户输入 Kotlin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68605999/