Reputation: 54949
I am trying to set a condition and set true or false as follows but it returns false all the time.
boolean checked = (categoriesCursor.getString(3) == "1") ? true
: false;
Log.i("Nomad",categoriesCursor.getString(3)+ " "+checked);
When i try to output the values i get the following.
01-12 00:05:38.072: I/Nomad(23625): 1 false
01-12 00:05:38.072: I/Nomad(23625): 1 false
01-12 00:05:38.072: I/Nomad(23625): 1 false
01-12 00:05:38.072: I/Nomad(23625): 1 false
01-12 00:05:38.072: I/Nomad(23625): 1 false
01-12 00:05:38.072: I/Nomad(23625): 0 false
01-12 00:05:38.072: I/Nomad(23625): 0 false
Upvotes: 17
Views: 47596
Reputation: 4148
Change it to this:
boolean checked = (categoriesCursor.getString(3).equals("1")) ? true : false;
Don't use ==
to compare String contents.
NOTE: The ==
operator can't be overloaded or modified in JAVA. If you are using object1 == object2
, where object1
and object2
are Strings or any other object, you'll checking whether the references point to the same underlying object. This will not compare the contents.
Upvotes: 1
Reputation: 3246
First there's no need for ternary operator. Then you must use equals()
instead of ==
. Because ==
operator checks whether the references to the objects are equal.
Upvotes: 1
Reputation: 1045
Try using this
(categoriesCursor.getString(3).equals("1")) ? true : false;
Upvotes: 3
Reputation: 29693
Use equals
instead of ==
boolean checked = (categoriesCursor.getString(3).equals("1"));
Upvotes: 3
Reputation: 61437
Firstly, to compare strings, you'll have to use the equals
method:
categoriesCursor.getString(3).equals("1")
Secondly, you don't need the ternary operator here. equals
already results in a boolean, so simply assign it:
boolean checked = categoriesCursor.getString(3).equals("1");
Upvotes: 1
Reputation: 81349
It returns false
all the time because you are comparing references, not strings. You probably meant this instead:
boolean checked = (categoriesCursor.getString(3).equals("1")) ? true
: false;
Which happens to be equivalent to this:
boolean checked = categoriesCursor.getString(3).equals("1");
And in case categoriesCursor.getString(3)
may be null
, you will be safer doing this instead:
boolean checked = "1".equals(categoriesCursor.getString(3));
Upvotes: 43