Home > OS >  How to check unique alias in cloud firebase?
How to check unique alias in cloud firebase?

Time:02-26

i want to check nick name in hashmap but i didn't get all document from cloud firebase? How can i do that? Thanks in advance.

val db = Firebase.firestore
val docRef = db.collection("User").document()
docRef.get().addOnSuccessListener { documents->
    
    if (documents != null) {

        val obj= documents.get("Basic Information") as HashMap<*, *>
        val checkNick= obj["nick"].toString()

        if (checkNick == nick){
            Toast.makeText(activity, "exists.", Toast.LENGTH_LONG).show()
        }

    } else {
        Log.d(TAG, "No such document")
    }
}

CodePudding user response:

This line of code creates a reference to a new, non-existing document:

val docRef = db.collection("User").document()

Since the document doesn't exist yet, calling docRef.get() leads to an empty snapshot.


If you want to load a specific document, you'll need to know its document ID and specify that in the call to document:

val docRef = db.collection("User").document("documentIdThatYouWantToLoad")

If you want to check whether any document exists in the collection for the given nickname, you can use a query:

val query = db.collection("User").whereEqualTo("nick", nick)

Since a query can get multiple documents, you also need to handle that differently:

query.get().addOnSuccessListener { documents ->
    if (!documents.empty) {
        Toast.makeText(activity, "exists.", Toast.LENGTH_LONG).show()
    }
    for (document in documents) {
        Log.d(TAG, "${document.id} => ${document.data}")
    }
}
.addOnFailureListener { exception ->
    Log.w(TAG, "Error getting documents: ", exception)
}

Also see:

  • Related