无法让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。
addListenerForSingleValueEvent
onDataChange()
要使其正常工作,您应该移动
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();