Question

I'm displaying the user score "right/tries" (es. 10/100) but I want to display it as % (es. 10%). Moreover I want it to be green if the score >= 90%, blue if the score is between 60% and 90% and red otherwise. With my code the score is green if the score is 100%, otherwise is red. It's never blue. (if I minimize the app and go back, sometimes is even black, the default value from xml).

My class call the changemyColor function in this way

 ....
int holderRight = sharedPrefs.getInt("Right", 0);
int holderTries = sharedPrefs.getInt("Tries", 0);
if ( holderTries != 0) { // to avoid n/0
changemyColor(holderRight,holderTries);
}

and this is the function

       public void changemyColor(int right, int tries) {
       TextView tvId = (TextView) findViewById(com.example.somma.R.id.score_field);
       int pino = 0; 

       double value = ((right / tries)*100) ;
       tvId.setText(getString(R.string.Score_capital) + sharedPrefs.getInt("Right", 0) + getString(R.string.Score_of) + sharedPrefs.getInt("Tries", 0));
       if (value >= 80) {
           pino = 1;
       } else if (value < 80 & value >= 30) {
               pino = 2;       
       } else if (value < 30) {
           pino = 3;
       }

       switch (pino){
       case 1:
           tvId.setTextColor(Color.GREEN);
           break;
       case 2:
           tvId.setTextColor(Color.BLUE);
           break;
       case 3:
           tvId.setTextColor(Color.RED);
           break;
       }       

   }

I also changed the code to

blabla.setText(value + " " + right + "/" + tries); 

And got as output

"1.0 1/1"
"0.0 1/2"
"0.0 2/3"
"0.0 3/4"
"0.0 4/5"
"0.0 5/6"
"0.0 6/7"
"0.0 7/8" 
"0.0 8/9"
"0.0 9/10"

I think I'm doing something wrong in the division line but I can't figure it out alone. Any help would be appreciated.

Was it helpful?

Solution

Since it's mobile, in case you wanted to still use int to use less resources on the device, (after realising that integer division is the default when using integers), you could perform the multiplication first so that you don't get rounded to 0:

int value = (right*100) / tries;

It won't be very accurate but you do have a range of values you're checking by anyway. Just a thought.

OTHER TIPS

if you want the accurate result you have to use

double value=(right*100)/(double)tries
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top