在我的主要活动中,我通过在整个数据库中搜索用户ID(...created_at":"2016-11-01 14:19:07"},{"sub_items":["subOne","subTwo","subThree"...
)来检查用户是否已注册到我的应用,但每次都是(即使用户ID已保存在数据库中),查询无法找到它。
user.getUid
这就是我的数据库的样子:
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user == null) {
//User is signed out
startActivity(intentlogin);
Log.d(TAG, "onAuthStateChanged:signed_out");
finish();
} else {
//User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
//has user Username?
String Userid = user.getUid();
Query usernamequery = mRef.orderByChild("Userid").equalTo(Userid);
usernamequery.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.exists()) {
//should go here when user id in database
// TODO: handle the case where the data already exists
return;
}
else {
//This is where it always lands
// TODO: handle the case where the data does not yet exist
startActivity(intentusername);
finish();
}
}
答案 0 :(得分:1)
请记住,即使您查询单个项目,查询也始终返回值列表。迭代这些值。
Query usernamequery = mRef.orderByChild("Userid").equalTo(Userid);
usernamequery.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot != null && snapshot.getChildren != null) {
//Define a model class for user that contains UserId and Username
for(DataSnapshot child : snapshot.getChildren()) {
Model model = child.getValue(Model.class);
//now, get the UserId and username from the model class
model.getUserId();
}
}
else {
//This is where it always lands
// TODO: handle the case where the data does not yet exist
startActivity(intentusername);
finish();
}
}