来自firebase的评级总价值的总和 [英] Sum of total value of rating from firebase

查看:54
本文介绍了来自firebase的评级总价值的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要什么样的方法才能在firebase中添加额定值的总量?在这里,我包括了我的Firebase的json结构.需要重点关注的是ratingstar_review.

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.

假设,第一个列表和第二个列表的ratingstar_review的总和为3 + 5 = 8.因此,我希望得到总计8.下面是从firebase检索数据的代码,这些数据将存储在Ratingbar上进行显示.

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!

推荐答案

这种方法应该可以解决问题:

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:

  • 由于/Ratings下有多个子节点,因此代码需要在这些子节点上循环.
  • 要从每个子项中获取值,请使用getChild("ratingstar_review")找到正确的属性,然后使用getValue(Integer.class)将其作为整数获取.
  • 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).

这篇关于来自firebase的评级总价值的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆