Getting list of items/children from Firebase Database?

firebase get list of data android
firebase get all child keys javascript
firebase get data by key android
firebase orderbychild
orderbychild firebase android
order by child firebase android
firebase get value of child
how to retrieve data from firebase in listview android

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:

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();
}

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.

Work with Lists of Data on Android, ChildEventListener, onChildAdded(), Retrieve lists of items or listen for additions to a list of items. This callback is triggered once for each existing child and then  If you have fewer than 100 items stored in your Firebase database, a child_added event fires for each item. As items change, you receive child_added events for items that enter the query and child_removed events for items that drop out of it so that the total number stays at 100.

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) {

                }
            });

Work with Lists of Data on the Web, child_added, Retrieve lists of items or listen for additions to a list of items. This event is triggered once for each existing child and then again every time a new  The ChildAdded event is typically used to retrieve a list of items in a Firebase database. The ChildAdded event is raised once for each existing child and then again every time a new child is added to the specified path. The listener is passed a snapshot containing the new child's data. The ChildChanged event is raised any time a child node is modified. This includes any modifications to descendants of the child node.

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) {

                }
            });

Getting list of items/children from Firebase Database?, The key elements of Firebase database list handling are the push() method, the Query class, child and value event listeners and a By joining the beta, you will get access to experimental features, at the risk of encountering bugs and issues. The child_added event is typically used when retrieving a list of items from the database. Unlike value which returns the entire contents of the location, child_added is triggered once for each existing child and then again every time a new child is added to the specified path. The event callback is passed a snapshot containing the new child's data.

Try this code:

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

Working with Firebase Realtime Database Lists, The database structure: For each dbRef of different sports, I have a child node So, I get DataSnapshot of the child (“contacts”), using the first highlighted line of The various types of the “Static Values” can also be used to read the real How would you store millions of key: value elements in a way that is fast to query​? If you have fewer than 100 items stored in your Firebase database, an onChildAdded() callback fires for each item. As items change, you receive onChildAdded() callbacks for items that enter the query and onChildRemoved() callbacks for items that drop out of it so that the total number stays at 100.

How to read all child key values of a child from Firebase database in , Firebase Database Get Reference From URL – get a Database Reference for the provided First – listen to node which is the list of items you want to display. See the following screenshots: The code: Here, dbRef is the database reference to the parent node. The database structure: For each dbRef of different sports, I have a child node “contacts”.

Firebase get all child keys, fetch reference database FirebaseDatabase mDatabase = FirebaseDatabase. a string to fetch the database reference for a unique key to add the list of objects. We can use the child() method to reach to a specific path of a snapshot. The push() method generates a key every time a new child is added. 2. Read List of Data. We can retrieve List that contains all Data items by collecting each item in Child Event onChildAdded() call back. There are some Child Events which are triggered when a child being updated through updateChildren() method.

Reading and writing to Realtime Database, a collaborative grocery list app (that basically requires a list of objects to be synced across users). If you use firebase database and add a value event listener to the chat parent node or grocery list parent node, you will So if you are keeping UI refreshed for say chat app, get the  About the Data List App Project. The project created in this chapter takes the form of a simple To Do list app in which items may be added to, or removed from a list stored in a Firebase realtime database. In addition to these features, the app will also allow the user to search for items contained in the list.

Comments
  • Thanks for your comment, Alex! So I've tried implementing your method and I think I need a bit of assistance. I decided to follow your video and make an ArrayList called imagesList, iterating through the for loop to add items to my ArrayList as they are got from dataSnapshot. I then tried to return imagesList.size() for getItemCount(), but it's not returning any images, as if the number is 0? I followed your method on creating the FirebaseCallback interface and everything, but there is no images populating my list. Is there something I might be doing wrong here?
  • I cannot be much of a help without seeing your code. So please edit your question by adding the code that you have tried so far.
  • I actually found a way to fix this issue last night, though it may not be very elegant. I created a SharedPreference, putting the childrenCount as the value in putInt and returned the value in getItemCount() and this works! The only caveat is that on a fresh install of the app, I need to call onFinish() and refresh the app once the Database info has been got and the SharedPreference has been set. I set a ProgressDialog to show on the first launch telling the user that the app is fetching images, right before onFinish() is called. Every launch after that works normally.
  • SharedPreferences doesn't persist across app uninstalls. So it's not the best idea. Seeing your code, I can say, it's almost correct, but you should pass to your onCallback method the count, if this is what you need. If you need the entire list, then everything looks fine to me. So if you are using Log.i("READ", list.size()); (size() not toString()) I'm sure it prints the correct size, right?
  • getItemCount() is an overriding method from inside your adapter class and has nothing to do with the async call. Are two different things. This is how you can get data from a Firebase real-time database and display it in a ListView using an ArrayAdapter.
  • This seems to be on the right track! I've been fiddling with this exact code, but I can't find a way to extract the given number from the onDataChange() block. Basically, I'm trying to use the number given, in this case 2, as the number returned for my Adapter in getItemCount(). Any ideas?
  • Do you want to use the number "num" as a number of your Adapter? so, if the num=2, you want the list to display 2 items, right?
  • Thanks for your comment, ikerfah! Your solution is very similar to Momen's and just as useful! Maybe you can also help me with how to extract count from this block of code so that it can be referenced and used outside this code as well? I'm looking at trying to use the number from getChildrenCount as the number used in my Adapter's getItemCount() method. Does that make sense?
  • In best practice you must return inside getItemCount the size of the datahandler ( An arrayList for example ), So you need to define a public method named for exemple setData(ArrayList<POJO> items) inside your adapter and pass the new data to it ( dont forget to call notifydatasetchanged() ) , or Simply you can define a public method inside the adapter named setItemCount and pass the count variable from onDataChange to it