user961389
user961389

Reputation: 423

Android logical operation &&?

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.

Upvotes: 2

Views: 13877

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503799

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.)

Upvotes: 12

Related Questions