0

I am developing a registration system using Firebase. I used the registration method with email and password. When a user registers he is registered as an account with the email and password, in addition all the data entered by him except the password (email, image link and username) will constitute a hereditary structure in the DB firebase realtime (the id which is assigned to the user will be the parent) in this way:

in this way

However, I must verify if the user enters an existing username. The problem is that I should go check on all the children and check if the value of them is equal to the username entered and, I do not know how to do this.

example of the value of children to be verified: example of the value of children to be verified

Can anyone suggest me a way to do this?

Code updated:

FirebaseDatabase.getInstance().getReference("Usernames").child(us.getText().toString()).setValue("Saved").addOnCompleteListener(new OnCompleteListener<Void>() {
    @Override
    public void onComplete(@NonNull Task<Void> task) {
        if(task.isSuccessful())
            Toast.makeText(getApplicationContext(), "Il nome non esiste",Toast.LENGTH_SHORT).show();
        else
            Toast.makeText(getApplicationContext(), "Il nome esiste",Toast.LENGTH_SHORT).show();
    }
});
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Jon snow
  • 5
  • 4
  • If you want to ensure that usernames are unique, you'll need a data structure where you use the username as the key of each node and (for example) the UID of the user as the value. Since keys are by definition unique within a parent, this automatically enforces the uniqueness of the user name. This has been covered a few times before, so I recommend checking out some of the answers to [similar questions](https://stackoverflow.com/search?q=%5Bfirebase-realtime-database%5D%5Bandroid%5D+unique+username) and reporting back if you get stuck. – Frank van Puffelen Jun 02 '21 at 20:17
  • @FrankvanPuffelen ok thanks for he advice – Jon snow Jun 02 '21 at 20:23
  • @FrankvanPuffelen Hello. I'm having trouble checking if the child has been created. To check if a user has entered an already existing username, I try as you advised me to insert all the users' usernames in a structure since if I go to insert a child that is the same as another, it does not insert it; but this is the point: how can I check if the child has not been inserted? because task is true and add on failure is always false. I have updated my code above – Jon snow Jun 03 '21 at 09:02
  • You'll need to: 1) [use a transaction](https://firebase.google.com/docs/database/android/read-and-write#save_data_as_transactions) in your code, to first check if the username exists before trying to write it, 2) use security rules to ensure a username cannot be overwritten if it already exists. Kato's answer [here](https://stackoverflow.com/a/25328654/209103) shows a good example of that. – Frank van Puffelen Jun 03 '21 at 13:34

0 Answers0