0

How do I retrieve all the fields of the current user logged?

enter image description here

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

enter image description here

RodParedes
  • 378
  • 1
  • 2
  • 12
  • 1
    Hmm. The answer it right in the getting started guide [Read Data](https://firebase.google.com/docs/firestore/query-data/get-data#get_a_document). Have you gone through that? If not, the Getting Started Guide really is the best place to Get Started. – Jay Nov 19 '21 at 21:17
  • @Jay Reading the guide, did not help sorry, I've just put this code var result= FbReference.collection("users").document("$userID").get() and nothing happend, when put this other line to retrieve the field of username, println("result is " +result.getResult()!!.getString("user")), it says that Task is not complete yet – RodParedes Nov 20 '21 at 02:19
  • `DocumentReference.get()` returns a task object. You need to add a completion listener to get notified when the data has been fetched from the firestore. – Arpit Shukla Nov 20 '21 at 04:55
  • 2
    See this line `println("8")` it will actually execute *before* the code within the Firebase closure, like this `userName = document!!` which means userName is undefined outside the closure. Code is faster than the internet and firebase data is only valid within the closure. [Firebase functions are asynchronous](https://stackoverflow.com/questions/47847694/how-to-return-datasnapshot-value-as-a-result-of-a-method/47853774) so you should read up on that as it's the core issue in your code. – Jay Nov 20 '21 at 14:24

1 Answers1

2

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.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Thank you Alex for the advice! I 've followed your instructions but the execution code completely ignores it, like as if it wasn't there. I added the current code with the console error, in case if I may missing something – RodParedes Nov 20 '21 at 14:07
  • 1
    This [answer](https://stackoverflow.com/questions/37618738/how-to-check-if-a-lateinit-variable-has-been-initialized) will help, right? – Alex Mamo Nov 20 '21 at 15:03
  • No, Alex that specfied answer does not, but jay commented a question that you have answer some time ago, that may think that it could be the problem. So, big Thanks!! – RodParedes Nov 20 '21 at 17:40
  • @AlexMamo document() requires a String datatype but you supplied a String? datatype, was there no error at your end? – oriohac Jan 17 '23 at 21:43
  • @oriohac Yes, document() requires a String datatype and I supplied a String. `"gA4z1AhkQpQ6J47sIMmCGIZRKDK2"` is a String. – Alex Mamo Jan 18 '23 at 08:01
  • what I mean is you supplied a String?. type, which is a string with null safety, here `val uid = auth.currentUser?.uid usersRef.document(uid).get().addOnCompleteListener {/* ... /*}` so how could that work? – oriohac Jan 18 '23 at 14:04
  • @oriohac Check [safe calls](https://kotlinlang.org/docs/null-safety.html#safe-calls) in Kotlin. – Alex Mamo Jan 18 '23 at 14:07
  • I know about safe calls, why I'm asking because it flagged an error when I tried that out, until I used `auth.currentUser!!.uid` which is a non-null asserted call. – oriohac Jan 18 '23 at 14:31