Reputation: 54
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. I wanted to save this information into google firestore. I have set up all the dependencies and I know I have it properly connected to google firebase. The issue I find is that every tutorial on this topic is different from one another, and every one I could find does not function 100%. Is there a way to save these 3 values into google firestore in kotlin and a way to retrieve these values in another activity?
Upvotes: 2
Views: 848
Reputation: 138824
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.
To get the data from these EditText objects, please use the following lines of code:
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.
To save the data in Firestore, the most simple solution would be to create a data class:
data class User(
var firstName: String? = null,
var lastName: String? = null,
var id: String? = null
)
Create an object of the class:
val user = User(firstName, lastName, id)
And write it to Firestore:
val rootRef = FirebaseFirestore.getInstance()
val usersRef = rootRef.collection("users")
usersRef.document(id).set(user).addOnCompleteListener(/* ... */)
Which will produce the following database schema:
Firestore-root
|
--- users (collection)
|
--- $id
|
--- firstName: "Abrahim"
|
--- lastName: "Mahmud"
|
--- id: "userIdIntroducedFromKeyboard"
To read the data back, simply make a get() call and attach a listener as shown below:
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)
}
And the result in the logcat will be:
Abrahim Mahmud
Upvotes: 3