Home > Mobile >  How to check if a document exist in firestore kotlin?
How to check if a document exist in firestore kotlin?

Time:10-06

I am trying to check if a document exists in Firestore. But I am getting the wrong result when I try to run the code. This is my code. Actually, there is no document corresponding to the document named currentUse in the collection. But I get that task is successful and Toast message appears as the document exists. Where might have I gone wrong and how to check a document exists in Kotlin.


 val currentUse= FirebaseAuth.getInstance().currentUser?.uid

 private val mFireStore = FirebaseFirestore.getInstance()
 val docref =mFireStore.collection("Users").document("$currentUse")

        docref.get().addOnCompleteListener {  task ->
            if (task.isSuccessful){
                Toast.makeText(applicationContext,"Exists",Toast.LENGTH_SHORT).show()

                startActivity(Intent(applicationContext, MainActivityUser::class.java))

            }


        }

CodePudding user response:

Actually there is no document corresponding to the document named currentUse in the collection. But I get that task is successful and the Toast message appears as the document exists.

If you only check if a Task is successful it doesn't mean that the document where the reference is pointing to actually exists. It means that your get() call is completed with no errors.

To check if a particular document exists, you should explicitly call exists() on the DocumentSnapshot object. So please use the following lines of code:

docref.get().addOnCompleteListener { task ->
    if (task.isSuccessful) {
        val document = task.result
        if(document != null) {
            if (document.exists()) {
                Log.d("TAG", "Document already exists.")
            } else {
                Log.d("TAG", "Document doesn't exist.")
            }
        }
    } else {
        Log.d("TAG", "Error: ", task.exception)
    }
}

CodePudding user response:

Note: If there is no document at the location referenced by docRef, the resulting document will be empty and calling exists on it will return false.

^ If you use addOnSuccessListener

And the below is for addOnCompleteListener

if (task.isSuccessful){
  if(task.result != null) {
    Toast.makeText(applicationContext,"Exists",Toast.LENGTH_SHORT).show()
    startActivity(Intent(applicationContext, MainActivityUser::class.java))
  }
}

It's all show in the examples here: https://firebase.google.com/docs/firestore/query-data/get-data

You can also read more here:

https://firebase.google.com/docs/reference/android/com/google/firebase/database/DatabaseReference

https://firebase.google.com/docs/reference/android/com/google/firebase/database/DatabaseReference.CompletionListener

  • Related