Search code examples
javafirebasefirebase-realtime-databasechildren

Firebase Java Android Check if a child was not created because it was the same as another already present in the same parent


I am developing a login and registration system with java for an android app. I use firebase to register users with email and password and the email, username and other information will form an inheritance structure on the realtime db firebase as parent there is the user id:

User data

However, I want the usernames to be unique and so that if a user writes a username already present in the parent Usernames he recognizes that there is another child that is the same. Since firebase doesn't allow you to create children with the same name I tried to do something like this:

FirebaseDatabase.getInstance().getReference("Usernames").child(us.getText().toString()).setValue("Saved").addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            Toast.makeText(getApplicationContext(), "Not same username", Toast.LENGTH_SHORT).show();
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText(getApplicationContext(), "same username", Toast.LENGTH_SHORT).show();
                        }
                    });

But I don't understand why, the answer is always OnCompleted, even when the child has the same name as another and therefore a user has entered a username already entered.

Could someone tell me how I can check if the Firebase db did not insert the child because it was named the same as another

Here are my current database rules:

{
  "rules": {
    ".read": "true",  
    ".write": "true",
  }
}

RTDB structure

Full Code: https://codeshare.io/Gq880j


Solution

  • You can check if the username exists yourself like this:

    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference("Usernames").child(us.getText().toString());
    rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
      @Override
      void onDataChange(DataSnapshot snapshot) {
        if (snapshot.exists()) {
          // Username is already taken
        } else {
          // Username is available, add the data
        }
      }
    });
    
    

    That's probably the easiest way to do it. If you use the update operation directly, it'll overwrite the existing values.