I have a rating bar which is supposed to display individual user rating average depending on which user is logged in. A user can rate another user by writing to the database under the rating node as shown here
The user who has been rated is under the node "ratee". please note '-LxW7A......' is a randomly generated key. To view the user's rating in the event that he has been rated more than once I have used the code below to get the sum of the ratings and divide that by the total amount of times the user has been rated to get the average
FirebaseUser user=mAuth.getCurrentUser();
String userId=user.getUid();
DatabaseReference refund =
FirebaseDatabase.getInstance().getReference("ratings");
Query query=refund.orderByChild("ratee").equalTo(userID);
final RatingBar ratingBar=(RatingBar)findViewById(R.id.ratingBar) ;
query.addValueEventListener(new ValueEventListener() {
int count=0;
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String rating=dataSnapshot.child("rater").getValue(String.class);
if (rating==null){Toast.makeText(getApplicationContext(),"empty ",Toast.LENGTH_SHORT).show();}else{
count=count+Integer.valueOf(rating);
double a = dataSnapshot.child("kutaPoints").getValue(double.class);
totalpointsused =+ a;
double tots=(double)count;
double result=totalpointsused/tots;
float abc=(float)result;
Toast.makeText(getApplicationContext(),""+abc,Toast.LENGTH_SHORT).show();
ratingBar.setRating(abc);
}}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
The code above however does not work and nothing is displayed in the rating bar and the toast empty is being displayed.
When you are using the following query:
Query query=refund.orderByChild("ratee").equalTo(userID);
It means that the DataSnapshot
object that you get as an argument in onDataChange()
method contains a list of results. Even if there is a single result, as I see in your screenshot, the list will contain a single element. So when talking about a list, to get the elements we need to iterate through the list. So please check the following lines of code:
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
long count = 0;
for(DataSnapshot ds : dataSnapshot.getChildren()) {
long ratingg = ds.child("ratingg").getValue(Long.class);
count = count + ratingg;
}
long avarage = count / dataSnapshot.getChildrenCount();
Log.d("TAG", "avarage: " + avarage);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
query.addListenerForSingleValueEvent(valueEventListener);
Assuming that all 4 users have the value of ratingg
property set to 4
, the result in your logcat will be:
avarage: 4