我在想方设法检索所有跟随我的用户。假设我是user1,user2和user3是我的追随者。我如何才能检索它们而不是检索所有用户并在客户端进行筛选?检索与Firebase双向关系的用户 - Android
这是我的结构看起来像:
{
"followers" : {
"user1" : {
"user2" : true,
"user3" : true
}
},
"following" : {
"user2" : {
"user1" : true
},
"user3" : {
"user1" : true
}
},
"users" : {
"user1" : {
"firstName" : "User One"
},
"user2" : {
"firstName" : "User Two"
},
"user3" : {
"firstName" : "User Three"
}
}
}
我没有任何的代码,但因为我不知道如何甚至开始。任何帮助表示赞赏。谢谢阅读。编辑: 这是我如何得到它的工作。我不知道这是不是最好的选择,但它现在起作用。
ChildEventListener childEventListener = new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());
// A new comment has been added, add it to the displayed list
String uid = dataSnapshot.getKey();
mDatabase.child("users").child(uid).addListenerForSingleValueEvent(
new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get user value
User user = dataSnapshot.getValue(User.class);
users.add(user);
notifyDataSetChanged();
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "getUser:onCancelled", databaseError.toException());
}
});
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildChanged:" + dataSnapshot.getKey());
// A comment has changed, use the key to determine if we are displaying this
// comment and if so displayed the changed comment.
//Comment newComment = dataSnapshot.getValue(Comment.class);
String commentKey = dataSnapshot.getKey();
System.out.println("Changed: "+commentKey);
notifyDataSetChanged();
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.d(TAG, "onChildRemoved:" + dataSnapshot.getKey());
// A comment has changed, use the key to determine if we are displaying this
// comment and if so remove it.
String commentKey = dataSnapshot.getKey();
System.out.println("Removed: "+commentKey);
notifyDataSetChanged();
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());
// A comment has changed position, use the key to determine if we are
// displaying this comment and if so move it.
//User user = dataSnapshot.getValue(User.class);
String commentKey = dataSnapshot.getKey();
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "postComments:onCancelled", databaseError.toException());
Toast.makeText(context, "Failed to retrieve followers.", Toast.LENGTH_SHORT).show();
}
};
mDatabase.child("followers").child(currentUser.getUid()).addChildEventListener(childEventListener);
使用addListenerForSingleValueEvent()方法检索数据。请参阅此链接https://firebase.google.com/docs/database/android/retrieve-data –
@Narender嘿,感谢您的快速回复,但这并不实际解决了我的问题。我遇到的问题是没有过滤数据的方式让我的追随者使用单个查询。 –
不,你必须重复这个循环意味着你将会得到chield项目,然后重复每个项目的cheild来获得子项目 –