My Firebase real Time Database structure for users is setup like this:
How can I check that the Username is not taken already? I could not find anything online that works. Thank you.
My Firebase real Time Database structure for users is setup like this:
How can I check that the Username is not taken already? I could not find anything online that works. Thank you.
First of all, I suggest the reading of this docs:
Now, whether your business rule need to check if already exists a username in the Users
node, you should create another node called usernames
and save them as a strings list, this way, the query became more simple. I'm saying something like:
Users:
foo1:...
foo2:...
usernames:
username1,
username2
You can do it like this:
fun checkUsername(callback: (result: Boolean?) -> Unit){
val database = Firebase.database.reference
val reference = database.child("Users")
reference.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
for (postSnapshot in dataSnapshot.children) {
val post = postSnapshot.getValue<User>()
userList.add(post)
}
callback(userList.any { x -> x.username == "check_username" })
}
override fun onCancelled(databaseError: DatabaseError) {
callback(null)
}
})
}