Cannot get Firebase to identify a username that has already been entered. The code below shows that I am trying to compare the username entered with a DataSnapshot of my database. The code doesn't seem to pick up usernames that are entered. Is the code wrong?
private boolean mSwitch = false;
public void checkInfo(View view){
checkUsernameIsUnique();
checkInformation();
if(mSwitch) {
Intent intent = new Intent(getApplicationContext(), MenuActivity.class);
saveUserInformation();
startActivity(intent);
}
}
public void checkUsernameIsUnique(){
String username = Username.getText().toString().trim();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usernameRef = rootRef.child("user_profile_info").child(userID);
Query checkName = usernameRef.equalTo(username);
checkName.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String name = Username.getText().toString().trim();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
if(name.equals(ds.child("username").getValue(String.class))){
Username.setError("Username Taken");
Username.requestFocus();
} else {
Toast.makeText(ProfileActivity.this, "Registered User", Toast.LENGTH_SHORT).show();
mSwitch = true;
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
if(Username.getText().toString().equals("")){
Username.setError("A Username is Required");
Username.requestFocus();
}
if(Username.length() < 5){
Username.setError("Username must be 5 characters minimum");
Username.requestFocus();
}
}
On button click I wish to be able to direct the user to the error, and until it is unique the page should not be pushed to the next activity.
The JSON tree if it helps
"user_profile_info" : {
"8FUV95JorVT26Gd1QFNUbxEf8O93" : {
"date_of_birth" : "2/5/1925",
"diet" : "Moderate",
"drinker" : "No",
"education" : "Masters Degree",
"exercise" : "3 - 5 Hours a Week",
"forename" : "Ben",
"gender" : "Male",
"have_alzheimers" : "No",
"have_diabetes" : "No",
"have_parkinsons" : "No",
"history_alzheimers" : "No",
"history_diabetes" : "No",
"history_parkinsons" : "No",
"marital_status" : "Single",
"smoker" : "No",
"surname" : "Dover",
"username" : "Maturity101"
}