我试图查询最后 5 个项目,然后只听新孩子。但是,当我添加新孩子时,childeventlistener 返回我之前查询的 thos 5 中的最后一个孩子。
query = myRef.orderByKey().limitToLast(5);
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// dataSnapshot is the "issue" node with all children with id 0
int oldSize = mData.size();
List<ChatMessageEntity> data = new ArrayList<>();
for (DataSnapshot issue : dataSnapshot.getChildren()) {
// do something with the individual "issues"
ChatMessageEntity chat = issue.getValue(ChatMessageEntity.class);
data.add(0,chat);
}
mData.addAll(data);
adapter.notifyItemRangeInserted(oldSize, mData.size());
}
query.addChildEventListener(newMessageListener);
}
@Override public void onCancelled(DatabaseError databaseError) {
}
});
对于这种类型的场景,您最好使用ChildEventListener
. 这有一个方法onChildAdded
,最初会为(最多)五个孩子调用,然后为以后添加的每个新孩子调用。
query = myRef.orderByKey().limitToLast(5);
query.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
ChatMessageEntity chat = issue.getValue(ChatMessageEntity.class);
data.add(0,chat);
adapter.notifyItemInserted(mData.size()-1);
}
...
@Override public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore these
}
});
上面的代码有效,但缺少处理previousChildName
(因为稍后到达的子项可能不会添加到列表的末尾)、onChildChanged
、onChildMoved
和onChildRemoved
。为所有这些添加处理是一项有趣的练习,但需要大量的工作,而且要正确处理也有点棘手。如果您想完成这项工作,我建议您查看RecyclerViewAdapter
in FirebaseUI及其工作马FirebaseArray
- 它们经过了很好的实战测试。
有关更多信息,请参阅有关侦听子事件的Firebase 文档。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句