How to use pagination to Firestore Query using timestamp

你。 提交于 2021-02-11 12:20:10

问题


I wanted to query firestore database with the timestamp recently posted For ex: I have collection of posts Indexed with timestamp ascending and descending order when the user opens the feed it will show the today's date(timestamp Today Descending ) Posts. when the user scrolls it fetches next 3 ids and so on and ends with last item of today.But without ending with last item post of today I wanted to show the next day posts and so on for last seven days so the recycler view will be endless like instagram or fb feed. the initial try method was to get the recently posted post alone of timestamp.

         private int limit = 3;
private int PostLimit = 1;
   
        private void ReadingPosts() {


    String userId = FirebaseAuth.getInstance().getUid();
    FirebaseFirestore db = FirebaseFirestore.getInstance();

    Calendar calendar = Calendar.getInstance();
    final Date currentTime = Calendar.getInstance().getTime();
    calendar.setTime(currentTime);
    calendar.add(Calendar.DAY_OF_YEAR, - 7);
    final Date pastThreeDays = calendar.getTime();

    followingList.add(userId);
    final CollectionReference UserRef = db.collection("UserPosts");
    Query query = UserRef.limit(limit);

    query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull final Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                for (QueryDocumentSnapshot documentSnapshot : task.getResult()) {

                    for (String id : followingList) {


                        if (documentSnapshot.getId().equals(id)) {
                            Log.d(TAG, "onComplete: IDS3 :" + id);
                            FirebaseFirestore db = FirebaseFirestore.getInstance();
                            CollectionReference PostRef = db.collection("UserPosts")
                                    .document(id)
                                    .collection("Posts");

                            Query query = PostRef.orderBy("timestamp", Query.Direction.DESCENDING).limit(PostLimit);

                            query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                                @Override
                                public void onComplete(@NonNull Task<QuerySnapshot> task) {

                                    if (task.isSuccessful()) {
                                        for (QueryDocumentSnapshot documentSnapshot1 : task.getResult()) {
                                            Posts posts = documentSnapshot1.toObject(Posts.class);
                                            postsList.add(posts);

                                        }
                                    }

                                    postsAdapter.notifyDataSetChanged();
                                    swipeRefreshLayout.setRefreshing(false);
                                }
                            })

                                    .addOnFailureListener(new OnFailureListener() {
                                        @Override
                                        public void onFailure(@NonNull Exception e) {
                                            Log.d(TAG, "onFailure: Failed to get the posts");
                                        }
                                    });
                        }
                    }

                    postsAdapter.notifyDataSetChanged();
                }

                lastVisible = task.getResult().getDocuments().get(task.getResult().size() - 1);

                RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {

                    @Override
                    public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                        super.onScrollStateChanged(recyclerView, newState);
                        if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
                            isScrolling = true;
                        }
                    }

                    @Override
                    public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                        super.onScrolled(recyclerView, dx, dy);
                        LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                        int firstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition();
                        int VisibleItemCount = linearLayoutManager.getChildCount();
                        int TotalItemCount = linearLayoutManager.getItemCount();

                        if (isScrolling && (firstVisibleItemPosition + VisibleItemCount == TotalItemCount) && !isLastItemReached) {
                            isScrolling = false;
                            Query nextQuery = UserRef.startAfter(lastVisible).limit(limit);
                            nextQuery.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                                @Override
                                public void onComplete(@NonNull Task<QuerySnapshot> task1) {
                                    if (task1.isSuccessful()) {
                                        for (QueryDocumentSnapshot documentSnapshot : task1.getResult()) {
                                            Log.d(TAG, "Works" + documentSnapshot.getId() + " => " + documentSnapshot.getData());
                                            for (String id : followingList) {

                                                if (documentSnapshot.getId().equals(id)) {
                                                    Log.d(TAG, "onComplete: IDS3 :" + id);
                                                    FirebaseFirestore db = FirebaseFirestore.getInstance();
                                                    CollectionReference PostRef = db.collection("UserPosts")
                                                            .document(id)
                                                            .collection("Posts");

                                                    Query query = PostRef.orderBy("timestamp", Query.Direction.DESCENDING).limit(PostLimit);


                                                    query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                                                        @Override
                                                        public void onComplete(@NonNull Task<QuerySnapshot> task) {

                                                            if (task.isSuccessful()) {
                                                                for (QueryDocumentSnapshot documentSnapshot1 : task.getResult()) {
                                                                    Posts posts = documentSnapshot1.toObject(Posts.class);
                                                                    postsList.add(posts);
                                                                }
                                                            }

                                                            postsAdapter.notifyDataSetChanged();
                                                        }
                                                    })

                                                            .addOnFailureListener(new OnFailureListener() {
                                                                @Override
                                                                public void onFailure(@NonNull Exception e) {
                                                                    Log.d(TAG, "onFailure: Failed to get the posts");
                                                                }
                                                            });
                                                }
                                            }


                                        }

                                        postsAdapter.notifyDataSetChanged();
                                        Log.d(TAG, "onComplete: resultSize " + task1.getResult().size());
                                        lastVisible = task1.getResult().getDocuments().get(task1.getResult().size() - 1);

                                        if (task1.getResult().size() < limit) {
                                            isLastItemReached = true;
                                        }
                                    }
                                }
                            });
                        }

                    }
                };
                post_recycler_view.addOnScrollListener(onScrollListener);


            } else {
                Log.d(TAG, "Error getting documents: ", task.getException());
            }
        }
    });

}

I tried doing this Query so can i get the last seven days But don't how to query it with paging:

  Query query = PostRef.whereLessThan("timestamp",currentTime).whereGreaterThan("timestamp",pastSevenDays);

Started learning about paging recently. So I used this reference to construct this whole method https://stackoverflow.com/a/50742175/4232013. so if anyone can guide me how can i achieve this way of paging would be great thanks!

来源:https://stackoverflow.com/questions/62927499/how-to-use-pagination-to-firestore-query-using-timestamp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!