Search code examples
androidudparduinopacketdatagram

if statement not working on String from SharedPreference( already tried "==" & ".equals" & ".equalsIgnoreCase")


I recieved the string from arduino using datagram packet and stored the value in my sharedpreference with variable Switch1.

byte[] rcvData = new byte[1024];
DatagramPacket rcvPacket = new DatagramPacket(rcvData, rcvData.length);
dtSocket.receive(rcvPacket);
rcvStr = new String(rcvPacket.getData());
saveStatusPreference(ResId.substring(1), rcvStr);

it works fine I recieve whether my pin is on or off and I can retrive my sharedpreference if what the status is because I printed it in an individual textview just to make sure. But still it won't compare and prints me error.

if(Switch1Status.equalsIgnoreCase("ON"))
{
  Switch1.setBackgroundResource(R.drawable.onleft1);
}
else if(Switch1Status.equalsIgnoreCase("OFF"))
{
 Switch1.setBackgroundResource(R.drawable.offleft1);
}
else
{
 textView.setText("Error");
}

I already tried .equals from "==" because I found out that's wrong when comparing string values. I can't find solution anymore if somebody knows what I'm doing wrong please help me.

Thanks!


Solution

  • It's standard to start variables with lower case in java ...but i'm going to assume your "Switch1Status" is a string variable. Its good to include the declaration of the variable being analyzed.

    Just do a System.out.println("Switch1case " + Switch1Case) and see what string its actually holding. It may not be reading the preferences at all.

    You can also call Switch1case.trim() to remove white space around the String, which can often sneak in, especially if reading from an editText or user input.