我已经尝试了数千次,以从每家餐厅获得价值,然后从每家餐厅的评分中获得平均值。这是我的Firebase,那里有3位用户对餐厅进行了评分:Firebase database这是我的Java代码:
private void displayRating(){mRatingBar.setVisibility(View.VISIBLE);mRatingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener(){@Override公共无效onRatingChanged(RatingBar ratingBar,浮动评分,布尔fromUser){final DatabaseReference mRatingDb = FirebaseDatabase.getInstance()。getReference()。child(namesList.get(pos))。child(“ rating”)。child(currentUserId);mRatingDb.setValue(rating);最终的DatabaseReference averageRatingDb = FirebaseDatabase.getInstance()。getReference()。child(namesList.get(pos))。child(“ Average”);
mRatingDb.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
double total = 0.0;
double count = 0.0;
double rating = ds.child(currentUserId).getValue(double.class);
total = total + rating;
count = count + 1;
double average = total / count;
averageRatingDb.setValue(average);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
});
}
出于某种原因,我觉得onDataChange()上的for循环根本无法正常工作。我无法获得任何评分,所以我可以计算平均评分。
我将如何从用户那里获取值,然后分别获取每个餐厅的平均值?
[如果有人可以帮助您,我很迷路。谢谢。
您可以尝试这样:
final DatabaseReference mRatingDb = FirebaseDatabase.getInstance().getReference().child(namesList.get(pos)).child("rating").child(currentUserId);
final DatabaseReference mQueryDb = FirebaseDatabase.getInstance().getReference().child(namesList.get(pos)).child("rating")
final DatabaseReference averageRatingDb = FirebaseDatabase.getInstance().getReference().child(namesList.get(pos)).child("Average");
double total = 0.0;
double count = 0.0;
mRatingDb.setValue(rating).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
mQueryDb.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
double rating = ds.getValue(double.class);
total = total + rating;
count = count + 1;
double average = total / count;
averageRatingDb.setValue(average);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
});
}
});