UPDATED
My current code to get records count:
commentRef.child(poi.Id).addListenerForSingleValueEvent(new ValueEventListener() {
@SuppressLint("NotifyDataSetChanged")
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
commentList.clear();
setProgressDialog();
if (isAdded()) {
counterValue = (int) snapshot.getChildrenCount();
setCounter(counterValue);
}
}
This returns me the record count.
If will modify with
public void onDataChange(@NonNull DataSnapshot snapshot) {
commentList.clear();
setProgressDialog();
if (isAdded()) {
counterValue = (int) snapshot.getChildrenCount();
setCounter(counterValue);
for (DataSnapshot comment_key : snapshot.getChildren()) {
String comentariu = comment_key.child("text").getValue(String.class);
}
}
}
from same snapshot will get information text field. And in same manner can get all fields data.
I concluded that although I want to receive only the number of records, the snapshot contains information about all the records in the database (so all the records are sent to me by the server) and only in my device is the total number of records obtained with snapshot.getChildrenCount().
What I want is to reduce the information I download from the server to the minimum necessary to save money. Downloading all information will artificially increase costs.
2
Answers
That’s not true. The code that you shared will only return the number of nodes that exist within the
comments
node, for all the posts the query returns. The code for getting all the records in the database looks like this:Which is quite different.
You aren’t receiving all the data from the database, but only what the query returns. If you think that you’ll get too many nodes as a result of the query, then I recommend you create and maintain a counter yourself. In that way, you’ll only have to read a single number and not perform a query.
The Firebase Realtime Database always returns the raw information as it exists at the node you load. It doesn’t support any kind of aggregation operation, such as counting the nodes.
This means that the only way to get the count of the nodes in the database (through the SDK) without downloading the data, is to actually store that count in the database and update it whenever you create or delete a node. That’s for example what this simple Cloud Functions sample does: Tracking the number of elements in a list.
Expanding your database to support a specific use-case is quite common in NoSQL databases. To learn more about this and other best practices, I recommend reading NoSQL data modeling and watching Firebase for SQL developers.
Also see: