0

My Firebase real Time Database structure for users is setup like this: Structure

How can I check that the Username is not taken already? I could not find anything online that works. Thank you.

Thilo Jaeggi
  • 87
  • 1
  • 9

2 Answers2

0

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
Vinicius Almada
  • 386
  • 3
  • 13
0

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)
        }
    })
}
Kasım Özdemir
  • 5,414
  • 3
  • 18
  • 35