Hello, this is Kotlin Beginner.
While playing with Firestore, I suddenly had a question.
The value of a field can be easily retrieved, but
Is there a way to get the text of the field itself?
I would like to take the blue square in the following image literally.
Any help would be appreciated.
DocumentSnapshot#getData() method, returns an object of type Map<String!, Any!>. To get the keys of a document, simply iterate through the Map object, as explained in the following lines of code:
val uid = FirebaseAuth.getInstance().currentUser!!.uid
val rootRef = FirebaseFirestore.getInstance()
val uidRef = rootRef.collection("users").document(uid)
uidRef.get().addOnSuccessListener { document ->
if (document != null) {
document.data?.let { data ->
data.forEach { (key, _) ->
Log.d(TAG, key)
}
}
} else {
Log.d(TAG, "No such document")
}
}.addOnFailureListener { exception ->
Log.d(TAG, "get failed with ", exception)
}
To obtain the following result in the logcat:
email
id
nickname
password
phone
Related
This question already has answers here:
How to check if a document exist in firestore kotlin?
(2 answers)
Closed last month.
I Have the same key M6LMD0D7oyW1ueNKU2c6sXcZZFd2 I just want to check if this is present or not in Firestore. How can I do this?
To check if a particular user (document) exists in a collection in Firestore, you can simply use a get() call and attach a complete listener. In code, it will be as simple as:
val uid = Firebase.auth.currentUser?.uid
val uidRef = Firebase.firestore.collection("users").document(uid)
uidRef.get().addOnCompleteListener {
if (it.isSuccessful) {
val document = task.result
if (document.exists()) {
Log.d(TAG,"The user already exists.")
} else {
Log.d(TAG, "The user doesn't exist.")
}
} else {
task.exception?.message?.let {
Log.d(TAG, it) //Never ignore potential errors!
}
}
}
This can be done with a simple get() query. For a more complex retrieval of a document like listening to live updates and performing filter operations please refer to the Firebase documentation.
val docRef = db.collection("users").document(user.userId) // Access userId
docRef.get()
.addOnSuccessListener { document ->
if (document != null) {
Log.d(TAG, "DocumentSnapshot data: ${document.data}")
} else {
Log.d(TAG, "No such document")
}
}
.addOnFailureListener { exception ->
Log.d(TAG, "get failed with ", exception)
}
So I want to retrieve a particular Document from a Collection in Firestore and assign the document to a variable so that i can use it in other activity.
Collection contains Users as documents.
FirebaseFirestore.getInstance().collection(Users).document(getCurrentUserID()).get() ....
Model class: USER
fun getCurrentUserID(): String {
var currentUser = FirebaseAuth.getInstance().currentUser
var currentUserID = ""
if (currentUser != null) {
currentUserID = currentUser.uid
}
return currentUserID
}
You can get your user with using code below, then you can do whatever you want with it.
FirebaseFirestore.getInstance()
.collection("Users")
.document(getCurrentUserID())
.get()
.addOnSuccessListener { document ->
val user = document.toObject(USER::class.java)!!
// Now we stored information to user variable.
// You can use it by simply calling user.name etc.
// If you want to use it out of this block,
// you need to send it there, example to a function
deleteUserDetails(user)
}
.addOnFailureListener { e ->
Log.e(
this.javaClass.simpleName,
"Error while getting user details.",
e
)
}
fun deleteUserDetails(user: USER) {
// Now you can use it here too.
// Example set a textView with user.name or etc.
textView.text = user.name
}
How do I retrieve all the fields of the current user logged?
I've watched many tutorials and questions, and some of them talk about the whole collection, others about similar topics, but found no info about this.
Thank you
UPDATE
Current Code:
fun getUserName_FireBase(){
if(userID==null){
println("The userID is null")
userID= getUserID()
println("The userId has been assigned and now is: " + userID.toString())
}
println("1")
val db = FirebaseFirestore.getInstance()
println("1a")
val usersRef = db.collection("users")
println("1b")
usersRef.document(userID.toString()).get().addOnCompleteListener { task ->
println("2")
if (task.isSuccessful) {
println("3")
val document = task.result
if(document!!.exists()){
println("4")
userName = document!!.getString("user").toString()
println("user is " + userName.toString())
}else {
println("5")
Log.d("Error", "This document does not exist")
}
}else {
println("6")
task.exception?.message?.let {
Log.d(TAG, it)
}
}
println("7")
}
println("8")
}
Console error
The error is given because later I need to acces to userName var that is supposed to be filled in that function
To be able to get user data, you have to create a reference that points to that document, perform a get() call and attach a listener, as seen in the following lines of code:
val db = FirebaseFirestore.getInstance()
val usersRef = db.collection("users")
usersRef.document("gA4z1AhkQpQ6J47sIMmCGIZRKDK2").get().addOnCompleteListener { task ->
if (task.isSuccessful) {
val document = task.result
if (document.exists()) {
val email = document.getString("email")
val pass = document.getString("pass")
val user = document.getString("user")
Log.d(TAG,"$email/$pass/$user")
} else {
Log.d(TAG, "The document doesn't exist.")
}
} else {
task.exception?.message?.let {
Log.d(TAG, it)
}
}
}
The result in the logcat will be:
barrooroor#gmail.com/paport/do3fe4232ef2
If "gA4z1AhkQpQ6J47sIMmCGIZRKDK2" is the ID of the user that comes from the authentication process, then instead of the hard coded ID, you can simply use:
val auth = FirebaseAuth.getInstance()
val uid = auth.currentUser?.uid
usersRef.document(uid).get().addOnCompleteListener {/* ... /*}
// 👆
Besides that, something more important, never store sensitive data as passwords in plain text. Malicious users might take advantage of that. Always use Firebase Authentication for that and secure the database using Firestore Security Rules.
I want to get data from the cloud firestore and have to store it to a string variable but unable to do so and need help.
This is below code
val db = FirebaseFirestore.getInstance()
val docRef = db.collection("SlideShowImages").document("1")
docRef.get()
.addOnSuccessListener { document ->
if (document != null) {
Log.d(TAG, "DocumentSnapshot data: ${document.data}")
} else {
Log.d(TAG, "No such document")
}
}
.addOnFailureListener { exception ->
Log.d(TAG, "get failed with ", exception)
}
getting this from database and I want Link to store to variable first_image
{about=FCB, link=https://firebasestorage.googleapis.com/v0/b/missionx-g6305.appspot.com/o/EVENTS%2FSlide%20Show%20Images%2FCurrent%2FFCB.jpg?alt=media&token=950c5200-c553-4639-b33e-2b91a220b19c}
And I want to store it in variable
val first_image : String
first_image = document.data.link
when I use this I am getting an error
and put the variable type var so you can modify value. Val only allowed to set value permenant to that variable.
private var first_image: String
and get image in your variable :
first_image = document.getString("link");
Read Difference between val and var.
i need to get data from object (named "0") in a document in firestore, is that possible ?
this is my code now:
val db = FirebaseFirestore.getInstance()
val docRef = db.collection("accessories")
.document("brand0")
docRef.get().addOnCompleteListener(OnCompleteListener<DocumentSnapshot> { task ->
if (task.isSuccessful) {
val document = task.result
val group = document.get("0") as ArrayList<String>
}
but casting Any to Arraylist is not possible, any other way to get these data ?
It looks like 0 is a an object type field. That means it'll be represented locally as a Map type object with strings as the keys for the properties it contains.
After some trials and errors this is what worked for me in the end, but I am not sure why. I am using kotlin in my current project.
fun getOwner(userId: String) {
val db = Firebase.firestore
val docRef = db.collection("users").document(userId)
docRef.get()
.addOnSuccessListener { document ->
if (document != null) {
Log.d(TAG, "DocumentSnapshot data: ${document.data}")
val data = document.data as Map<String, String>
showOwnerName.text = data["name"]
} else {
Log.d(TAG, "No such document")
}
}
.addOnFailureListener { exception ->
Log.d(TAG, "get failed with ", exception)
}
}
I am converting the data I am getting to a map and this is how I am able to access its values.