ArclightOne
ArclightOne

Reputation: 39

Getting list of items/children from Firebase Database?

I'm running into some trouble figuring out how to get the number of items/children in my Firebase real-time database for my app to use as an int value.

Check the image below:

enter image description here

So as you can see above, I have 2 children of images_list.

What I want to do is: get the number of items/children of images_list returned to my app, which would obviously equal 2 initially, and have this number expand whenever I add more items/children.

So my question is, what code do I implement to grab the number of children in this database? And how could I then convert this number into an int value? I've already experimented with differing methods, but I haven't found a solution as of yet.

I hope that made sense. Thanks so much for any of your assistance!


Code solution down here; I had to move most of this code from my RecyclerView Adapter into my MainActivity for it to work

Interface

public interface FirebaseCallback {
    void onCallback(List<String> list);
}

readData method

private void readData(final FirebaseCallback firebaseCallback) {
    mDatabaseImagesRef = FirebaseDatabase.getInstance().getReference("images_list");
    ValueEventListener valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for (DataSnapshot ds : dataSnapshot.getChildren()) {
                String imageItems = ds.getValue(String.class);
                imageList.add(imageItems);
            }

            firebaseCallback.onCallback(imageList);
            Log.i("imageList.size() is: ", String.valueOf(imageList.size()));
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Log.i(LOG_TAG, databaseError.getMessage());
        }
    };
    mDatabaseImagesRef.addListenerForSingleValueEvent(valueEventListener);
}

called in onCreate()

readData(new FirebaseCallback() {
        @Override
        public void onCallback(List<String> list) {
            mImageAdapter.notifyDataSetChanged();
        }
    });

getItemCount() in RecyclerViewAdapter

@Override
public int getItemCount() {
    return imagesList.size();
}

Upvotes: 1

Views: 471

Answers (4)

AJ Seraspi
AJ Seraspi

Reputation: 113

Try this code:

public void onDataChange(@NonNull DataSnapshot snap) {
        int count = (int) snap.getChildrenCount();
        //shows the number of items
}

Upvotes: 0

Alex Mamo
Alex Mamo

Reputation: 138944

To count the all the children beneath images_list node, please use the following lines of code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference imagesListRef = rootRef.child("images_list");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        int count = (int) dataSnapshot.getChildrenCount(); //Cast long to int
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage());
    }
};
imagesListRef.addListenerForSingleValueEvent(valueEventListener);

how could I then convert this number into an int value?

According to the official documentation, getChildrenCount() method returns a long and not an int. So you need to cast that primitive long to an int.

how to extract count from this block of code so that it can be referenced and used outside this code as well?

You cannot simply create the count variable as a global variable and use it outside the onDataChange() method because it will always be 0 due the asynchronous behaviour of this method. This means that if try to use its result outside this method, the data hasn't finished loading yet from the database and that's why is not accessible. With other words, your count will always be 0.

A quick solve for this problem would be to use the value of your count variable only inside the onDataChange() method, otherwise I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.

Upvotes: 1

ikerfah
ikerfah

Reputation: 2862

mRef= FirebaseDatabase.getInstance().getReference("images_list");

on your "onDataChange" method inside the listener , use getChildrenCount() to get the number of images, you can iterate those children using i loop , Exmeple :

mRef.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    int count = dataSnapshot.getChildrenCount();
                   // here you get your images number

                  for(DataSnapshot ds : dataSnapshot.getChildren()) {
                      String key = ds.getKey()
                      // and here you get the key
                   }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

Upvotes: 0

Momen Zaqout
Momen Zaqout

Reputation: 1498

try this

userReference = FirebaseDatabase.getInstance().getReference("images_list");
userReference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    num = dataSnapshot.getChildrenCount();
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

Upvotes: 0

Related Questions