-2

I have a class named Player. There are a few player objects stored inside this class and every object has a "name", "score" and "color". I made a method that is supposed to set a TextView color according to which object I am dealing with. Here's the code:

public void setTextViewColor(TextView tw, String playerColor){

    Log.i("TAG", playerColor);

    if (playerColor == "BLACK")
    {
        tw.setTextColor(Color.BLACK);
        Log.i("TAG", "tw color now black");
    }
    else if (playerColor == "BLUE")
    {
        tw.setTextColor(Color.BLUE);
        Log.i("TAG", "tw color now blue");
    }
    else if (playerColor == "CYAN")
    {
        tw.setTextColor(Color.CYAN);
    }
    else if (playerColor == "DKGRAY")
    {
        tw.setTextColor(Color.DKGRAY);
    }
    else if (playerColor == "GRAY")
    {
        tw.setTextColor(Color.GRAY);
    }
    else if (playerColor == "GREEN")
    {
        tw.setTextColor(Color.GREEN);
    }
    else if (playerColor == "LTGRAY")
    {
        tw.setTextColor(Color.LTGRAY);
    }
    else if (playerColor == "MAGENTA")
    {
        tw.setTextColor(Color.MAGENTA);
    }
    else if (playerColor == "RED")
    {
        tw.setTextColor(Color.RED);
    }
    else if (playerColor == "YELLOW")
    {
        tw.setTextColor(Color.YELLOW);
    }
}

Now the problem is that the IF or ELSE statement never gets to execute. This is how I called the method:

setTextViewColor(newTextView, newPlayer.color);

The method is supposed to work because everytime I execute it, I can see the logcat message stating the color (the color is always correct). But I never see the "tw color now black" or "tw color now blue" message so I'm pretty sure there is something wrong with IF statement.

If the tag says the playerColor is "BLACK", then the first if statement is supposed to execute, right? But it doesn't.

Guy
  • 6,414
  • 19
  • 66
  • 136
  • you have to use `equals()` method. – Simon Dorociak Sep 01 '13 at 15:02
  • Thank you, works like a charm! I can't believe I did such a stupid mistake, I am well aware that you have to compare strings with equals(). – Guy Sep 01 '13 at 15:06
  • If you're using Java 7 you can also use a switch. That said, it really looks like you're just translating, meaning you should just use a `Map`. – Dave Newton Sep 01 '13 at 15:07

1 Answers1

1

You must use .equals():

if(playerColor.equals("BLACK"))

As user gunar mentioned, this is safer(because playerColor may be null):

"BLACK".equals(playerColor)