我在我的博客应用程序中添加了评论功能。我检索了RecyclerView的评论,并在较新的评论显示顶部时orderBy("timestamp")
。
我使用Firebase Firestore,在检索所有评论后。当用户发布新评论时,我希望评论显示在顶部。但通常评论添加了列表底部,因此它基本上显示在回收器视图的底部。
我使用以下代码显示新评论顶部但不幸的是,所有评论都转到Else
语句而不是新评论:
if (isFirstLoad) {
userList.add(userInfo);
commentList.add(commentInfo);
}else{
userList.add(0, userInfo);
commentList.add(0, commentInfo);
}
检索注释的整个代码:
Query query = db.collection("BlogPosts/" + postId + "/Comments").orderBy("timestamp", Query.Direction.DESCENDING);
query.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
if (queryDocumentSnapshots!=null && !queryDocumentSnapshots.isEmpty()){
for (DocumentChange doc: queryDocumentSnapshots.getDocumentChanges()){
if (doc.getType() == DocumentChange.Type.ADDED){
final BlogCommentInfo commentInfo = doc.getDocument().toObject(BlogCommentInfo.class);
String BlogUserId = doc.getDocument().getString("user_id");
db.collection("Users").document(BlogUserId).get().addOnCompleteListener(CommentActivity.this, new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()){
UsersInfo userInfo = task.getResult().toObject(UsersInfo.class);
if (isFirstLoad) {
userList.add(userInfo);
commentList.add(commentInfo);
}else{
userList.add(0, userInfo);
commentList.add(0, commentInfo);
}
adapter.notifyDataSetChanged();
}else{
Toast.makeText(CommentActivity.this, "Error: "+task.getException(), Toast.LENGTH_LONG).show();
}
}
});
}
}
}
isFirstLoad = false;
}
});
请帮我解决这个问题。
或者,如果您有任何其他方法可以显示回收器视图顶部的新评论,请告诉我。
只需按 ACCENDING 顺序对时间戳进行命中查询:
将查询从-
查询查询 = db.collection("BlogPosts/" + postId + "/Comments"(.orderBy("timestamp", Query.Direction.DESCENDING(;
自-
查询查询 = db.collection("BlogPosts/" + postId + "/Comments"(.orderBy("timestamp", Query.Direction.ASCENDING(;
或反转您的评论列表