How to count unique child value in firebase database?(please see the image , Thank you)

Prasath :

enter image description hereenter image description here

I created one android application in this application, I want to count unique child value.

I created for loop inside the database reference and assign global variable but the thing is I don't know how many unique values will become to my calculation(HOw many variables).

dbcloud.addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
    for(DataSnapshot dataSnapshot1:dataSnapshot.getChildren())
    {
        Modelfortotalsoldcount mc=dataSnapshot1.getValue(Modelfortotalsoldcount.class);
        String name=mc.getFoodname();
        String qty=mc.getFoodqty();
        String price=mc.getFoodprice();
        int totalcount=0;
        if(fname.equals(name))
        {
            String fgname=name;
            String fgprice=price;
            Integer intqty=Integer.valueOf(qty);
            totalcount=totalcount+intqty;
            String totalval=String.valueOf(totalcount);
        }
    }
  }
  @Override
  public void onCancelled(@NonNull DatabaseError databaseError) {
Alex Mamo :

Assuming that all those objects are direct children of your Firebase root, to solve this, please use the following query:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.orderByChild("foodname").equalTo("Burger");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        int count = 0;
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String foodqty = ds.child("foodqty").getValue(String.class);
            count = count + Integer.valueOf(foodqty);

        }
        Log.d(TAG, "count:" + count);
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
    }
};
query.addListenerForSingleValueEvent(valueEventListener);

The result in the logcat will be:

count: 4

Edit:

If you don't know the food name then you should use a variable instead:

Query query = rootRef.orderByChild("foodname").equalTo(foodName);

In which the foodName is what the user types in a EditText for example:

String foodName = foodNameEditText.getText().toString();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=327906&siteId=1