Sum of total value of rating from firebase

2019-06-12 03:19发布

What kind of approaches needed to add the total amount of rating value in firebase? Here i have included the json structure of my firebase. The one needed to be focused on are ratingstar_review.

enter image description here

Supposedly, the sum of ratingstar_review from first list and second would be 3+5=8. So I would expected to get that total sum 8. Below is the code for retrieving data from firebase to be stored on ratingbar for display.

    starRef.child("number_rating").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot != null && dataSnapshot.getValue() != null) {
                float rating = Float.parseFloat(dataSnapshot.getValue().toString());
                star.setRating(rating);
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) { }
    });

An example would be a helpful. Thank you!

1条回答
The star\"
2楼-- · 2019-06-12 03:38

Something like this should do the trick:

starRef.child("Ratings").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        int total = 0, 
            count = 0;
        for (DataSnapshot child: dataSnapshot.getChildren()) {
            int rating = dataSnapshot.child("ratingstar_review").getValue(Integer.class);
            total = total + rating;
            count = count + 1;
        }
        star.setRating(total);
    }
    @Override
    public void onCancelled(DatabaseError databaseError) { 
        throw databaseError.toException(); // don't ignore errors
    }
});

The main differences with your code:

  • Since there are multiple child nodes under /Ratings the code needs to loop over these children.
  • To get the value from each child, you find the correct property with getChild("ratingstar_review") and then get it as an integer with getValue(Integer.class).
查看更多
登录 后发表回答