【发布时间】:2018-01-20 12:10:46
【问题描述】:
我在尝试对 firebase 数据库中的数据进行分页数周时遇到了一个很好的问题,但都无济于事。我尝试了从 android 文档到 SO 的所有示例,但仍然无法正常工作。下面是我的数据节点的截图
以下是我的代码,我正在使用 recycleview 进行连续滚动。
commentDatabaseReference = FirebaseDatabase.getInstance().getReference().child(CHANNEL_COMMENT).child(postId);
commentDatabaseReference.orderByKey().limitToLast(TOTAL_ITEM_EACH_LOAD).addListenerForSingleValueEvent(commentValueEventListener);
ValueEventListener commentValueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.hasChildren()) {
currentPage--;
}
int counter = 0;
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
commentId = snapshot.getKey();
Comment comment = snapshot.getValue(Comment.class);
commentList.add(comment);
adapter.notifyDataSetChanged();
}
//adapter.notifyDataSetChanged();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
Recycleview 持续滚动监听器
recyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(linearLayoutManager) {
@Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
Log.e("more", "onload");
loadMoreData();
}
});
private void loadData() {
Log.e("loading", ""+ commentId);
commentDatabaseReference.orderByChild("timestamp").startAt(commentId).limitToLast(TOTAL_ITEM_EACH_LOAD)
.addListenerForSingleValueEvent(commentValueEventListener);
}
private void loadMoreData(){
//if ((currentPage * TOTAL_ITEM_EACH_LOAD) <= commentCount) {
currentPage++;
loadData();
//}
}
结论:例如,如果我有 20 个偏移量为 10 的数据,并且我使用带有 limitToLast 的 orderby,我会从顶部开始获得最后 10 个数据,即我从 11 - 20 而不是 20 - 11 获得数据。另外注意到有时当我与 startAt 结合时我会得到无休止的数据
【问题讨论】:
标签: android firebase-realtime-database pagination android-recyclerview