0

In my Android app I am using this code to retrieve posts from firebase database:

ArrayList<Post> posts = new ArrayList<>();
dbRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for(DataSnapshot dsp : dataSnapshot){
                   String author = dsp.child("author").getValue().toString();
                   String text = dsp.child("author").getValue().toString();
                    posts.add(new Post(author,text));
            }
                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

But this returns all the posts and if there would be many of them I think it wouldn't be good idea to keep them all in memory. Is there a way to get only certain number of node's children? For example at the beginning I would like to get 10 first ones, then 10 more and so on

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
matip
  • 794
  • 3
  • 7
  • 27

2 Answers2

1

You need to use your DataSnapShot to retrieve more specific information.

There is a Firebase guide for Android that explain how to utilize: Firebase Android Guide

If you would prefer to see on Stack OverFlow a small example this answer here seems to be doing somewhat of what you would like to achieve: Firebase Get Children

halfer
  • 19,824
  • 17
  • 99
  • 186
L1ghtk3ira
  • 3,021
  • 6
  • 31
  • 70
1

You're looking for limitToFirst() (or limitToLast()).

ArrayList<Post> posts = new ArrayList<>();
Query query = dbRef.orderByKey().limitToFirst(10);
query.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot dsp : dataSnapshot){
               String author = dsp.child("author").getValue().toString();
               String text = dsp.child("author").getValue().toString();
                posts.add(new Post(author,text));
        }
            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

See the Firebase documentation on queries for an explanation of all its capabilities.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807