This is my database. I want to check if a particular uid exists before adding so that I can avoid duplicate entries of the same uid. This is my code. It checks if the uid exists and then returns a boolean. which is parsed into an if statement in another method to add the contact. However, this method only returns false, even if the uid already exists in the contacts. Therefore allowing the adding of the same entry.
The method to check if contact exists.
public void addContacts(final String emailInput){
DatabaseReference users;
users = FirebaseDatabase.getInstance().getReference("users");
users.orderByChild("email").equalTo(emailInput).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference("users");
for (DataSnapshot emailSnapshot : dataSnapshot.getChildren()) {
String emailData = emailSnapshot.child("email").getValue(String.class);
final String name = emailSnapshot.child("name").getValue(String.class);
String role = emailSnapshot.child("role").getValue(String.class);
if (emailData.equals(emailInput)){
key = emailSnapshot.getKey();
System.out.println(key);
if ((!role.equals(userRole))) {
DatabaseReference contactRef = ref.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("contacts").child(key);
contactRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.child(key).exists()) {
ContactProfile newContact = new ContactProfile(key, name);
ref.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("contacts").push().setValue(newContact);
Toast.makeText(Contacts.this, "Contact Added Successfully", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(Contacts.this, "Contact Already Exists", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
else if(key.equals(FirebaseAuth.getInstance().getCurrentUser().getUid())){
Toast.makeText(Contacts.this, "You cannot add yourself",Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(Contacts.this, "Cannot add user. \n They have the same role",
Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(Contacts.this, "Cannot add user. \n User does not exist",
Toast.LENGTH_SHORT).show();
}
}
}