Search code examples
androidwidgetaveragerates

how to use rating widget and average the rates - android


I'm playing around with the rating widget in android. I know how to pull out the rating number from the rating widget but if I have more than one rates and I want to average the rates. How can I do that?

This is what I have at the moment.

    RatingBar ratingBar = (RatingBar) findViewById(R.id.ratingBar1);
    ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
        @Override
        public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
            TextView rate_lotr_number = (TextView)findViewById(R.id.rate_number1);
            rate_lotr_number.setText(String.valueOf(rating));

        }
    });

    RatingBar ratingBar1 = (RatingBar) findViewById(R.id.ratingBar2);
    ratingBar1.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
        @Override
        public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
            TextView rate_lotr_number = (TextView)findViewById(R.id.rate_number2);
            rate_lotr_number.setText(String.valueOf(rating));

        }
    });

I know I could probably use a look a some arrays to make a loop so to reduce all those repeating texts but I want to try how to average the rates before trying to reduce the redundancy.

EDITED: so what I want to ask how can I calculate the average of many ratingbars


Solution

  • You can get each rating value using RatingBar.getRating(), sum all the values and divide it by the number of rating bars.

    RatingBar ratingBar = (RatingBar) findViewById(R.id.ratingBar1);
    RatingBar ratingBar1 = (RatingBar) findViewById(R.id.ratingBar2);
    
    float total = 0;
    total += ratingBar.getRating();
    total += ratingBar1.getRating();
    float average = total / 2;
    

    Is this what you want? Please comment to avoid misunderstanding. Thank you.