我想计算Firebase数据库节点中想要显示在文本框中的所有评级值(浮点数)的总和。
Firebase数据库
Firebase DATABASE Preview
我想要检索的评级值。我想要所有评级值的总和,并在文本框中保存该总和值。
这就是我所做的事。
数据库类
public class databaseReview {
String description,name,userImage;
String rating;
public databaseReview(){
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public databaseReview(String rating, String description) {
this.rating = rating;
this.description = description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getuserImage() {
return userImage;
}
public void setuserImage(String userImage) {
this.userImage = userImage;
}
}
Java类
DatabaseReference dataReference =
FirebaseDatabase.getInstance().
getReference().child("Feedbacks").child(name);
dataReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for( DataSnapshot ds :dataSnapshot.getChildren()) {
databaseReview data = ds.getValue(databaseReview.class);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
});
答案 0 :(得分:2)
假设Feedbacks
节点是Firebase根目录的直接子节点而name
变量的值为Abasyn University Islamabad
,要计算所有评级,请使用以下代码:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference nameRef = rootRef.child("Feedbacks").child(name);
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
double count = 0;
for(DataSnapshot ds : dataSnapshot.getChildren()) {
double rating = ds.child("rating").getValue(Double.class);
count = count + rating;
}
Log.d("TAG", count + "");
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
nameRef.addListenerForSingleValueEvent(eventListener);
但请注意,仅当raiting
属性作为double
存储在数据库中时,此方法才有效。您的屏幕截图是正确的,但您的模型类显示:
String rating;