我有一个具有以下结构的数据库:
/users:
L-4ndxd58sqEwarvinW: <-- randomly generated id
name: henk
birthdate: 14-05-2016
L-4ndxd58sqEdgygorW:
name: priscilla
birthdate: 14-05-2016
/friends:
L-4ndxd58sqEwarvinW: <-- user id (henk)
L-4ndxd58sqEdgygorW: true, <-- friends user id (priscilla)
L-4ndxd58sqphysBW: true,
我当前的变量:
mFriendDatabase = FirebaseDatabase.getInstance().getReference().child("friends").child(mCurrent_user_id);
mFriendDatabase.keepSynced(true);
mCurrent_user_id = mAuth.getCurrentUser().getUid();
基本上,我想检索mCurrent_user_id的朋友的ID,并在Users数据库中搜索这些用户。
答案 0 :(得分:2)
这应该可以解决问题:
mCurrent_user_id = mAuth.getCurrentUser().getUid();
mFriendDatabase = FirebaseDatabase.getInstance().getReference("friends").child(mCurrent_user_id);
DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("users");
mFriendDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot friendKeySnapshot: dataSnapshot.getChildren()) {
String friendKey = friendKeySnapshot.getKey();
usersRef.child(friendKey).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot friendSnapshot) {
String friendName = friendSnapshot.child("name").getValue(String.class);
System.out.println(friendName);
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
嵌套的侦听器有些复杂,但是流本身应该很容易遵循。