我正在使用Android应用程序,该应用程序允许用户从多个Firebase数据库读取数据。

由于某些原因,数据没有按日期排序,而是随机排列。如何按日期对评论进行排序,并在列表的底部显示最新的评论?

ArrayList<Comment> comments = new ArrayList<Comment>();

ChildEventListener childEventListener = new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
    Comment comment = dataSnapshot.getValue(Comment.class);
    comments.add(comment):
}

@Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
    Comment newComment = dataSnapshot.getValue(Comment.class);
    String commentKey = dataSnapshot.getKey();
}

@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
    String commentKey = dataSnapshot.getKey();
}

@Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
    Comment movedComment = dataSnapshot.getValue(Comment.class);
    String commentKey = dataSnapshot.getKey();
}

@Override
public void onCancelled(DatabaseError databaseError) {
}
};


  List<String> dbUris = getFirebaseUriList();
    for(String dburi: dbUris){
        Query query = FirebaseDatabase.getInstance(dburi).getReference().child("comments").limitToLast(15);
        query.addChildEventListener(listener);

    }


在多个查询上使用相同的侦听器是个好主意吗?谢谢。

最佳答案

更改此:

  query.addChildEventListener(listener);


到这个:

 query.orderByChild("date").addChildEventListener(listener);


能够按date排序数据

更多信息在这里:
https://firebase.google.com/docs/reference/android/com/google/firebase/database/Query

10-08 06:35
查看更多