问题
I want to ask how to retrieve group that only user2 join in Android?
"users": {
"user1": {
"name": "User 1"
},
"user2": {
"name": "User 2"
}
}
"groups": {
"groupA": {
"name": "A Group"
},
"groupB": {
"name": "B Group"
}
}
"userGroup": {
"user1": {
"groupA": true,
"groupB": true
},
"user2": {
"groupB": true
}
}
I already try
DatabaseReference userGroupRef = rootRef.child("userGroup/user2")
but cannot show the name of the groups
But if I use
DatabaseReference groupsRef = rootRef.child("groups")
the group that user2
not joining also showing.
Does firebase has a query like groupsID in userGroup/user2
?
Edit_1
I use FirebaseRecyclerAdapter
to show the list from rootRef.child("groups")
that shows all the groups even if user2 is not joining.
groupsRef = rootRef.child("groups");
FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<Group, GroupHolder>(Group.class, R.layout.group_item_layout, GroupHolder.class, groupsRef) {
@Override
protected void populateViewHolder(GroupHolder viewHolder, Group group, int position) {
viewHolder.setGroupName(group.getName());
}
};
groupRecyclerView.setAdapter(adapter);
回答1:
This use-case is specifically addressed by the FirebaseIndexRecyclerAdapter. You pass in two references/queries: one for the so-called index (the keys with true
values that you want to show) and one for the actual object that you want to load for each matching key.
In your case:
groupsRef = rootRef.child("groups");
indexRef = rootRef.child("userGroup/user2");
FirebaseIndexRecyclerAdapter adapter = new FirebaseIndexRecyclerAdapter <Group, GroupHolder>
(Group.class, R.layout.group_item_layout, GroupHolder.class, indexRef, groupsRef) {
@Override
protected void populateViewHolder(GroupHolder viewHolder, Group group, int position) {
viewHolder.setGroupName(group.getName());
}
};
来源:https://stackoverflow.com/questions/42467195/how-to-retrieve-data-from-firebase-database-with-join-if-key-only-return-true