Firebase android pagination

后端 未结 10 1552
天命终不由人
天命终不由人 2020-11-28 09:14

I\'m building an app which will show videos stored on firebase. The list of videos needs to be paginated fetching most recent 20 videos at a time.

Here is

10条回答
  •  广开言路
    2020-11-28 09:20

    If you want to get list from firebase realtime database descending with pagination you need use smth like this:

    Query query = myRef.child("stories").orderByChild("takenAt").endAt(1600957136000L).limitToLast(30);
    

    Full code, two requests

            List storyList = new ArrayList<>();
            
            FirebaseDatabase database = FirebaseDatabase.getInstance();
            DatabaseReference myRef = database.getReference();
            
            //first request will be look like this
            Query query = myRef.child("stories").orderByChild("takenAt").endAt(1600957136000L).limitToLast(30);
            query.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    if (dataSnapshot.exists()) {
                        for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                            Story story = snapshot.getValue(Story.class);
                            storyList.add(story);
                        }
                    }
                    Collections.reverse(storyList);
                }
                @Override
                public void onCancelled(@NonNull DatabaseError error) {
                    Log.e("ptg", "onCancelled: ", error.toException());
                }
            });
            
            //second request
            long lastTakenAtInTheStoryList = storyList.get(storyList.size()-1).getTakenAt();
            Query query2 = myRef.child("stories").orderByChild("takenAt").endAt(lastTakenAtInTheStoryList).limitToLast(30);
            query2.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    if (dataSnapshot.exists()) {
                        for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                            Story story = snapshot.getValue(Story.class);
                            storyList.add(story);
                        }
                    }
                    Collections.reverse(storyList);
                }
                @Override
                public void onCancelled(@NonNull DatabaseError error) {
                    Log.e("ptg", "onCancelled: ", error.toException());
                }
            });
    

提交回复
热议问题