0

I have a problem in this code The tv.setText(str); is working and the text for tv change to "LED1", but in if(str=="LED1") it's not working! What is the problem?

Handler = new Handler()
{
    @Override
    public void handleMessage(Message msg)
    { 
        byte [] data= (byte[]) msg.obj;
        try {
            tv.setText("");
            String str = new String(data, "UTF-8");
            tv.setText(str);
            if(str=="LED1")
            {
                tv.setBackgroundColor(getResources().getColor(R.color.red));
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
};
Tarik
  • 4,961
  • 3
  • 36
  • 67
Hasan Hadi
  • 31
  • 1
  • 8

2 Answers2

1

You need to use equals instead of == for a String.

Which mean if(str.equals("LED1")) instead of if(str=="LED1")

See How do I compare strings in Java?

Community
  • 1
  • 1
Tarik
  • 4,961
  • 3
  • 36
  • 67
1

The issue occurs because you are using == operators to compare to strings. You need to use equals to match the string. As we require to compare the values.

change the below line

if(str=="LED1")

to

if("LED1".equals(str))
Vivek Singh
  • 2,047
  • 11
  • 24