2

I have a database of sport products. Users can add as many products as they want, as long as the products are correct and are approved by the admin. Everything works fine but in the last month, I checked the app and it start to work very slow. I checked that on real device as well as in an emulator. Same behaviour. I think that the problem is that the number of products is constantly growing and to count the products is even harder. Can anyone help me solve this problem? Thanks!

Code:

FirebaseDatabase.getInstance().getReference("sport_products").addListenerForSingleValueEvent(
        new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                int productCount = (int) dataSnapshot.getChildrenCount();

                for(DataSnapshot productSnapshot : dataSnapshot.getChildren()) {

                    //Code to process the data

                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError de) {}
        }
);
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Mee Noi
  • 99
  • 1
  • 8

1 Answers1

0

This depends on how much data (products) you have under sport_products node and what bandwidth you have on the device that you're retrieving it on.

So this is going to be slower than necessary, since you're retrieving all the actual products instead of just a simple counter. To solve this, I recommend you keep a separate counter for all products somewhere in the database, so you can update it, each time a users adds or removes a product. While this takes more code to track the number of products, reading it will become much easier.

Assuming that you have a database that looks like this:

Firebase-root
    |
    --- productCounter: 500
    |
    --- sport_products
           |
           --- productId
                 |
                 --- //Product details

You can add the counter right under the database root. To get the counter, simply attach a listener on productCounter property and get the value from the DataSnapshot object. Since you might use this app in a multiuser environment, I recommend you to increase / decrease the counter using Firebase Transaction as explained in my answer from this post.

Edit:

The methods that are apart of a ChildEventListener will be triggered on the individual child nodes and don't carry knowledge of the entire result. The only way to get the product count of your sport_products node is to keep your own counter in code and increment it in onChildAdded() method and decrement it in onChildRemoved() method. This gives you a counter of how many children your client-code has already processed.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193