Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android logical operation &&?

Tags:

java

android

This one has been giving me fits for over an hour... I could swear the code is right. Am I missing something?

if((fType != "EXACT") && (dateTime > System.currentTimeMillis())){ 
    myIntent = new Intent(getBaseContext(), MyScheduledReceiver1.class);                        
} else {
    myIntent = new Intent(getBaseContext(),MyScheduledReceiver2.class);
}

Even if the String fType is "EXACT" & long dateTime is in the future... it's still calling MyScheduledReceiver1.class... when since 1 is false it should be calling MyScheduledReceiver2.class.

like image 255
user961389 Avatar asked Jan 28 '26 06:01

user961389


1 Answers

The problem is probably that you're comparing string references rather than comparing the values within the strings:

if (!fType.equals("EXACT") && dateTime > System.currentTimeMillis()) {
    ...
}

That will now call the equals method on the string, which will compare whether the two character sequences are equal, rather than just whether fType and "EXACT" refer to the exact same String object.

(That will throw an exception if fType is null; if you want it to just not match you could use if (!"EXACT".equals(fType) && ...) - it depends on the situations.)

like image 107
Jon Skeet Avatar answered Jan 30 '26 21:01

Jon Skeet