-1

enter image description here

I have strings stored in SQLite database which are shown in an Activity. the problem is if I compare the text of the button with a string value it returns false while equals show it matches. I am curious to know who it is returning false while they are both the same.

I have tried and tostring methods.

while (result.moveToNext()) {

 Button btn = new Button(this);
 btn.setWidth(100);
 btn.setHeight(40);
 //    btn.setSingleLine(); //keep text in single line don't break big words
 //    btn.setAutoSizeTextTypeUniformWithConfiguration(1, 15, 1,
 //          TypedValue.COMPLEX_UNIT_DIP);
 messageReceived = result.getString(1).trim();
 btn.setText(result.getString(1).trim());


 String btnText = btn.getText().toString().trim();


 String Value = Boolean.toString(btnText == messageReceived);
 Toast toast = Toast.makeText(this, Value, Toast.LENGTH_LONG);
 toast.setGravity(Gravity.CENTER, 5, 5);
 toast.show();

 if (messageReceived.equals(btnText)) {
  Toast toast2 = Toast.makeText(this, "matched", Toast.LENGTH_LONG);
  toast2.setGravity(Gravity.LEFT, 0, 0);
  toast2.show();
 } else {
  Toast toast2 = Toast.makeText(this, "Not Matched", Toast.LENGTH_LONG);
  toast2.setGravity(Gravity.LEFT, 0, 0);
  toast2.show();
 }


 Toast.makeText(this, "A: " + btn.getText() + " B: " + messageReceived, Toast.LENGTH_LONG).show();

 btn.setOnClickListener(this);
 grid.addView(btn);

 //messageReceived="pungi";

 if (btnText == messageReceived) {
  btn.setBackgroundColor(Color.YELLOW);
 }


}
shb
  • 5,957
  • 2
  • 15
  • 32
Yugraaj Sandhu
  • 392
  • 3
  • 14

3 Answers3

4

It probably because == compare addresses when equal compares content example

String s1 = new String("sd"); 
String s2 = new String("sd");
System.out.println(s1 == s2); 
System.out.println(s1.equals(s2));

First return false when second return true

Nikunj Paradva
  • 15,332
  • 5
  • 54
  • 65
CodeNight
  • 114
  • 3
1

This line btnText==messageReceived will always return a false as both are not pointing to same object.

equals method match the content where as == operator match the object pointing to same address. Read out this document to know more about == and equals. == vs equals

Hope this helps you

Rajnish suryavanshi
  • 3,168
  • 2
  • 17
  • 23
1

Oh, this is a good one. Boolean.toString(stringA == stringB) is actually doing a reference comparison; that is, checking if both objects are pointing to the same memory location. String.equals(), on the other hand, compares the values.

String A = new String("five");
String B = new String("five");

System.out.println(Boolean.toString(A == B)); // false.

System.out.println(Boolean.toString(A.equals(B))); // true

Also, the Boolean.toString(A.equals(B)) can be replaced by A.equals(B), which will return a Boolean in the same sense.