Q:

How do i prevent duplicate usernames on firebase database

I'm really new to firebase. I've been reading similar topics here but I still don't get it.
Here's what I'm trying to do:

I'm making a simple authentication with
email + password + username. And I store the usernames on my database (please see the image)
(https://i.stack.imgur.com/eQxZM.png)

I made the parent key to uid and the key: value  both to username cause I read that if you do that it'll not allow same keys but I don't understand, it still overwrites the key and values
My Firebase rules is set to read write true cause this is just a sample project. I hope someone can help me. Thanks!!

A:

I would recommend you to make your database structure like following:
rootReference
|
 -- uid1
 |
  - username
 |
  - email
 |
  - other_details
|
 -- uid2
 |
  - username
 |
  - email
 |
  - other_details

This database structure not only would help you make every child unique but it would also help you search for user with particular username or email that you may need to get in future.
This database structure makes it easy to query with orderByChild() and also stores your username and email under uid.
For finding if a username is unique or not, you may use a simple query with orderByChild() like following:
reference.orderByChild("username").equalTo(userNameYouWantToSearch).addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                            if(dataSnapshot.exists())
                             // do what you want
                        }

                        @Override
                        public void onCancelled(@NonNull DatabaseError databaseError) { // ToDo: do something for errors

                        }
                  )};

In if() statement, you can just tell that userNameYouWantToSearch already exists on database and hence is not unique.

