【发布时间】:2017-11-20 11:43:28
【问题描述】:
我正在尝试验证用户名是否已存在于 Firebase 数据库中并创建了一个方法来验证它。
如果用户名可用,该方法应返回 true,如果用户名已被使用,则返回 false。
public boolean isUsernameValid(final String newUsername, String oldUsername){
if(newUsername.equals(oldUsername)){
//if username is not changed
return true;
}else {
userValid = true;
databaseReference.orderByChild("Username").equalTo(newUsername).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
long userCount = dataSnapshot.getChildrenCount();
if(userCount!=0){
userValid = false;
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
return userValid; //username is valid if this returns true
}
}
此方法首先返回 UserValid 布尔值,然后查询数据库。如果我遗漏了什么,请告诉我。
这首先返回 true,然后在数据库中搜索用户名,因此,它总是覆盖数据库中的用户名。
从这里调用这个方法:
if(!TextUtils.isEmpty(str_firstName)
&& !TextUtils.isEmpty(str_lastName)
&& !TextUtils.isEmpty(str_username)
&& verify.isEmailValid(str_email)
&& verify.isMobileNoValid(str_mobile)
//here
&& verify.isUserNameValid(str_username, globalSharedPrefs.getUserDetail("username").toString())){
progressDialog.setMessage("Saving Profile ...");
progressDialog.show();
//saving the photo
if(isImageClicked) {
filepath = storageReference.child("profile_photos").child(globalSharedPrefs.getUserDetail("uid").toString());
filepath.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//TODO: add picture remote/edit button in the XML
isImageClicked = false;
downloadUri = taskSnapshot.getDownloadUrl();
databaseReference.child("Profile Picture").setValue(downloadUri.toString());
uploadUserInfo();
Toast.makeText(UserProfileActivity.this, "Profile Saved.!", Toast.LENGTH_LONG)
.show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
progressDialog.dismiss();
updateProfileUI();
clickEditProfileButton(false);
Toast.makeText(UserProfileActivity.this, "Update Failed.!", Toast.LENGTH_LONG)
.show();
}
});
}
数据库结构
{
"userinfo" : {
"J6Y4Dtxe7Nh45B653U5AVXHFrSJ2" : {
"AccountId" : "",
"DOB" : "21 Jun, 2017",
"First Name" : "Krishna",
"Last Name" : "kk",
"Mobile" : "",
"Username" : "kittuov",
"uid" : "J6Y4Dtxe7Nh45B653U5AVXHFrSJ2"
},
"ck8x94FeHtUbC9DgHCkxmQt93Ar1" : {
"AccountId" : "",
"DOB" : "7 Dec, 1992",
"First Name" : "Seshagiri Rao",
"Last Name" : "Kornepati",
"Mobile" : "",
"Username" : "seshu1",
"uid" : "ck8x94FeHtUbC9DgHCkxmQt93Ar1"
},
"iDBn0lYIZFSgll9KyVje0T6JFIy2" : {
"AccountId" : "",
"DOB" : "",
"First Name" : "Ramesh",
"Last Name" : "Devarapu",
"Mobile" : "",
"Username" : "rameshb",
"uid" : "iDBn0lYIZFSgll9KyVje0T6JFIy2"
}
}
【问题讨论】:
-
Firebase 异步加载数据。这意味着当你的
return语句执行时,数据还没有加载(通过设置断点来尝试)。有关更广泛的解释,请在此处查看我的答案:stackoverflow.com/questions/33203379/…
标签: android firebase firebase-realtime-database nosql