I am trying to add some users in my real time firebase data base, I want to check that by email address which is an User attribute, the problem is that it is adding duplicates. I have an button To add in my database
DAOUser daoUser = new DAOUser();//database accessObject
registerAccountButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (emailField.getText().toString().equals("") || passwordField.getText().toString().equals("") || repeatPasswordField.getText().toString().equals("")) {
Toast.makeText(getApplicationContext(), "Please complete all fields!", Toast.LENGTH_SHORT).show();
} else if (!Objects.equals(passwordField.getText().toString(), repeatPasswordField.getText().toString())) {
Toast.makeText(getApplicationContext(), "Passwords does not match!", Toast.LENGTH_SHORT).show();
} else {
addUser(daoUser, emailField.getText().toString(), passwordField.getText().toString());
}
}
});
The method to add in database:
public void addUser(DAOUser daoUser, String inputMail, String inputPassword) {
daoUser.getDatabaseReference().child("User").orderByChild("email").equalTo(inputMail).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
Toast.makeText(getApplicationContext(), "User already exists!", Toast.LENGTH_SHORT).show();
} else {
User newUser = new User(inputMail, inputPassword, false);
try {
daoUser.add(newUser).addOnSuccessListener(suc -> {
Toast.makeText(getApplicationContext(), "Successfully registered user!", Toast.LENGTH_SHORT).show();
}).addOnFailureListener(er -> {
Toast.makeText(getApplicationContext(), "Unable to register user!", Toast.LENGTH_SHORT).show();
});
} catch (UserIsNullException e) {
e.printStackTrace();
System.out.println("User is null");
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(getApplicationContext(), "User DataBase error !", Toast.LENGTH_SHORT).show();
}
});
}