Friday 17 November 2017

if statement comparing strings in java android













I'm
trying to write a method in az DBOpenHelper extends SQLOpenHelper class.
It
supposed to evaluate if there's an entry in the DB with the same name.



public boolean
existsContact(Contact contact) {

SQLiteDatabase db =
this.getReadableDatabase();
String selectQuery = "SELECT * FROM " +
TABLE_CONTACTS;
Cursor cursor = db.rawQuery(selectQuery,
null);

if (cursor.moveToFirst()) {
do
{

String name = cursor.getString(1);
String cname =
contact.getName();
if (name == cname) {


cursor.close();
db.close();
return true;


}

} while (cursor.moveToNext());

}

db.close();

return
false;
}



Here's
the relevant part of Contact
class:



 public class Contact
{

String _name;
public String getName(){

return this._name;
}

}



Now
here's the strange thing:



Scenario A :
if (name == cname) where name = "foo"
and cname = "foo" equals false.
Eclipse debugger
show name's foo and cname's foo have different id's.
both variables filled as
seen before in code.



Scenario B:
if(name == cname) where variabales are loaded like
this:




String name =
"foo";
String cname = "foo";
statement equals true as it's supposed
to.


Scenario C:
if("foo" == "foo") equals true...BUT...debugger goes out the
window. LogCat show debugger connected, but there's no activity in eclipse's Debug
perspective. Breakpoints have no effect. No Threads shown.



Answer




In java, when using
== on two objects, you're not actually comparing the strings
themselves. You'll need to use
.equals(String).



==
actually compares the two object's references, not their
values.




string1.equals(String
target)
compares the two strings based off of the actual characters in the
strings.



See: href="http://www.leepoint.net/notes-java/data/expressions/22compareobjects.html">http://www.leepoint.net/notes-java/data/expressions/22compareobjects.html



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...