In my app I have to verify that there are not more than two users with the same name. I tried it with the following code, but when it detects that the user who tries to register already exists, it appears a toast that indicates to change it.
The problem is that even if you know that name already exists and although the toast appears, the account is created without importing the imposed condition, thus creating two users with the same username.
How could I avoid that, that two users with the same name will be created?
regBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
regBtn.setVisibility(View.INVISIBLE);
loadingProgress.setVisibility(View.VISIBLE);
final String email = userEmail.getText().toString();
final String password = userPassword.getText().toString();
final String password2 = userPAssword2.getText().toString();
final String name = userName.getText().toString();
if(verificationUsername(name)){
showMessage("ass");
regBtn.setVisibility(View.VISIBLE);
loadingProgress.setVisibility(View.INVISIBLE);
}
public boolean verificationUsername (String equalto){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("Users").orderByChild("username").equalTo(equalto);
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String TypeUser = dataSnapshot.child("username").getValue().toString();
if (dataSnapshot.exists()) {
System.out.println(TypeUser + "dssssssssssssssssssssssssddddddsssssssssssssssssssssss");
lola = dataSnapshot.toString();
showMessage("El nombre de usuario ya esta en uso, intenta con uno nuevo");
// dataSnapshot is the "issue" node with all children with id 0
for (DataSnapshot issue : dataSnapshot.getChildren()) {
// do something with the individual "issues"
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
return false;
}