简体   繁体   中英

Retrieve count data from Firebase Java

I am trying to count the number of children in my DB table that meet a certain condition. If the isSeen column equals false then I want to count that, if it equals true I don't want to count it.

Currently, it's not working but if I change the query from Query query = usersRef.orderByChild("isSeen").equalTo(true); to Query query = usersRef.orderByChild("isSeen"); I get a number but it's not the correct way. Can someone please help me?

 {
  "DIt5bGqw2WS4eGHNqQJKxZSn3B72": {
    "b3vYlKZFrje0e3wHyBlWIK4ooK93": {
      "-N8MfBR4gu5G4kMF9fGW": {
        "dateAdded": 1659328311354,
        "date_time": "Aug-01-2022 12:31:51 AM",
        "from": "b3vYlKZFrje0e3wHyBlWIK4ooK93",
        "isSeen": false,
        "message": "Cool",
        "to": "DIt5bGqw2WS4eGHNqQJKxZSn3B72",
        "type": "text"
      },
      "-N8NCgnwX6V7ghfGlcWS": {
        "dateAdded": 1659337356887,
        "date_time": "Aug-01-2022 3:02:36 AM",
        "from": "DIt5bGqw2WS4eGHNqQJKxZSn3B72",
        "isSeen": false,
        "message": "Hello",
        "to": "b3vYlKZFrje0e3wHyBlWIK4ooK93",
        "type": "text"
      }
    }
  },

FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();

    DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("Messages");
    Query query = usersRef.orderByChild("isSeen").equalTo(true);
    ValueEventListener valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot ds : dataSnapshot.getChildren()) {

                long count = ds.child(firebaseUser.getUid()).getChildrenCount();
                //Toast.makeText(MainActivity.this, "In here.", Toast.LENGTH_SHORT).show();
                //long count = ds.child("isSeen").getChildrenCount();
                Log.d("TAG", "Count:" + count);
            }
        }

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

Try this

Log.e(dataSnapshot.getKey(),dataSnapshot.getChildrenCount() + "");

I think you should try this, it working for me. It read your messages for the first time

usersRef.orderByChild("isSeen").equalTo(true).addListenerForSingleValueEvent(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot snapshot) {
     Log.d("TAG", "Count:" + String.valueOf(dataSnapshot.getChildrenCount()));
  }
  @Override
  public void onCancelled(DatabaseError databaseError) {        
  }
});

When you're using the following query:

Query query = usersRef.orderByChild("isSeen").equalTo(true);

Firebase will always return the exact data you are querying, meaning that you'll get all elements that have the isSeen field set to true . Please note that there is no way you can query by a negation. So something like this is not possible:

Query query = usersRef.orderByChild("isSeen").notEqualTo(true);
//                                               👆

According to your comment in which you say that you don't have any elements where the isSeen field is set to true , then your query will yield no results, and that's the expected behavior.

While @TimothyPham's answer will work, using getChildrenCount() might be the best solution. Why? Because if you have a lot of messages this operation requires you to read all of them in order to provide a number. The best solution I can think of would be to increment/decrement a counter as explained in my answer from the following post:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM