![](/img/trans.png)
[英]How to check if username already exists in firebase Realtime Database
[英]How to check if username exists in my firebase database already?
無法使Firebase識別已經輸入的用戶名。 下面的代碼顯示我正在嘗試將輸入的用戶名與數據庫的DataSnapshot進行比較。 該代碼似乎沒有拾取輸入的用戶名。 代碼是否錯誤?
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();
}
}
在按鈕上單擊,我希望能夠將用戶引導到該錯誤,並且在該錯誤唯一之前,不應將該頁面推送到下一個活動。
JSON樹(如果有幫助)
"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"
}
addListenerForSingleValueEvent
是一個異步操作。 設置回調onDataChange()
,代碼將繼續運行,而您尚未獲取任何用戶名。 到您檢查mSwitch值時,即使用戶名確定,它也始終為false。
為了使其正常工作,您應該移動
checkInformation();
if(mSwitch) {
Intent intent = new Intent(getApplicationContext(), MenuActivity.class);
saveUserInformation();
startActivity(intent);
}
到onDataChange()
回調的末尾。
另外,最好在查詢文檔之前先檢查空字符串和長度。 只是為了減少從數據庫下載的無用數據。
但是由於for循環,它似乎仍然無法正常工作。 像這樣嘗試:
mSwitch = true; // as its OK
for (DataSnapshot ds : dataSnapshot.getChildren()) {
if(name.equals(ds.child("username").getValue(String.class))){
mSwitch = false;
Username.setError("Username Taken");
Username.requestFocus();
break;
}
}
...
if (mSwitch) startActivity();
else showErrorToast();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.