-4

Probably this will be so stupid to be asked, but I can't find the way to make it works and even to find the solution on Internet.

I need to concatenate 2 strings (variable STR_Prefix and string "TA+") to create a new one ("ATA+" or "BTA+"), then I have to check the value in an if-statement, but it fails, the if-statement doesn't detect the "ATA+".

But if I set the value of "STR_Action" directly to "ATA+" it works perfectly.

public void Test(boolean ok)
{
    String STR_Action = "";
    if (ok) { STR_Prefix = "A"; }
    else    { STR_Prefix = "B"; }

    /* I have tried some ways to concatenate */
    STR_Action = STR_Prefix + "TA+";    // Not working with the if-statement
    // STR_Action = new StringBuilder(STR_Prefix).append("TA+").toString();    // Not working with the if-statement

    /* But if-statement only works when I set STR_Action directly with = "ATA+" or "BTA+"; */
    // STR_Action = "ATA+";    // This assign is detected by the if-statement

    if (STR_Action == "ATA+")
    {
        Toast.makeText(getApplicationContext(), "ATA+", 0).show();
    }
    else if (STR_Action == "BTA+")
    {
        Toast.makeText(getApplicationContext(), "ATA-", 0).show();
    }
    else
    {
        Toast.makeText(getApplicationContext(), "Code not found", 0).show();
    }
}

Please, help :'(

Thanks in advance

1 Answers1

3

try this way used .equals() method for String comparison

 if (STR_Action.equals("ATA+"))
M D
  • 47,665
  • 9
  • 93
  • 114
  • Thanks M D, it works perfect. But I still don't understand what is the difference between: STR_Action = STR_Prefix + "TA+"; STR_Action = "ATA+"; Both means that STR_Action = "ATA+" but "if" doesn't work in the same way for both when ussing "==": - Concatenation: fails - Direct assign: works – Alberto Hernández de la Huerta Dec 29 '14 at 06:14