【发布时间】:2016-08-27 03:04:10
【问题描述】:
我正在尝试找出一种方法来检索所有关注我的用户。假设我是 user1,user2 和 user3 是我的关注者。我怎样才能只检索它们而不是检索所有用户并在客户端过滤它们?
这是我的结构的样子:
{
"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() 方法检索数据。参考此链接firebase.google.com/docs/database/android/retrieve-data
-
@Narender 嘿,感谢您的快速回复,但这实际上并不能解决我的问题。我遇到的问题是没有一种方法可以过滤数据以使用单个查询来获取我的关注者。
-
不,您必须重复循环意味着您将获得子项,然后重复每个项的子项以获取子项
-
@Narender 我已经编辑了我的代码。这是你的意思吗? (顺便说一句,这是有效的)
标签: java android json firebase firebase-realtime-database