-3

I'm trying to show average of 3 ratingBars using Toast but it always show 0.0. I also tried to convert the average to String but no luck. Please help. Here is my code:

float rating1 = ratingBar.getRating();
float rating2 = ratingBar2.getRating();
float rating3 = ratingBar3.getRating();
float average = (rating1+rating2+rating3) / 3;

final String formatFloat = Float.toString(average);

Button button1 = (Button) rootView.findViewById(R.id.button1);
button1.setOnClickListener(new android.view.View.OnClickListener() {
    public void onClick(View v) {
    // Implement your logic here

    Toast.makeText(PlaceholderFragment.this.getActivity(),formatFloat, 
                        Toast.LENGTH_SHORT).show();             
    }
});
PankajAndroid
  • 2,689
  • 3
  • 27
  • 41
GSng
  • 1
  • 3

4 Answers4

1

Looks like you're losing precision. Try this:

float average = (rating1+rating2+rating3) / (float)3;
bstar55
  • 3,542
  • 3
  • 20
  • 24
1

The button code will be executed until the user click that button, all the previously code will be executed before the button setup. When are the ratings bar changed? After or before the button is set up? I would do

Button button = (Button) rootView.findViewById(R.id.button1);
button.setOnClickListener(new android.view.View.OnClickListener() {
  public void onClick(View v) {
    float rating1 = ratingBar1.getRating();
    float rating2 = ratingBar2.getRating();
    float rating3 = ratingBar3.getRating();
    float average = (rating1 + rating2 + rating3) / 3.0f;
    String formatFloat = Float.toString(average);
    Toast.makeText(PlaceholderFragment.this.getActivity(),formatFloat,
                   Toast.LENGTH_SHORT).show();
  }
}

To ensure the ratings are the latest values when the user click the button, otherwise, such as your code, rating1, rating2 and rating3 could be all 0 if the code is executed before the user changes the rating bars.

nigonzalezm
  • 190
  • 2
  • 10
0

I tried this code by putting hard code values and it is working good

    float rating1 = 13.4f;
    float rating2 = 12.6f;
    float rating3 = 19.5f;
    float average = (float) ((rating1 + rating2 + rating3) / 3);

    final String formatFloat = Float.toString(average);

    Log.i("mini", "Rating:"+formatFloat);

try this!!!

Meenal
  • 2,879
  • 5
  • 19
  • 43
0

Can you just add the calculation part of ratings inside the setOnClickListener and check? Like below.

Button button1 = (Button) rootView.findViewById(R.id.button1);
button1.setOnClickListener(new android.view.View.OnClickListener() {
    public void onClick(View v) {
    // Implement your logic here

float rating1 = ratingBar.getRating();
float rating2 = ratingBar2.getRating();
float rating3 = ratingBar3.getRating();
float average = (float)((rating1+rating2+rating3) / 3);

    Toast.makeText(getApplicationContext(),average + "", 
                        Toast.LENGTH_SHORT).show();             
    }
});
Aniruddha
  • 4,477
  • 2
  • 21
  • 39