0

My piece of code is

                String gps = "gps";
            if (loc.getProvider() == gps){
                forCampaignCopy.setText(loc.getProvider());
                locationManager.removeUpdates(locationListener); //to stop using the sensor
            }
            else{
                forCampaignCopy.setText(loc.getProvider());
            }

When I run the debugger, it stops at the if statement and I can see that loc.getProvider() says gps (since that is the provider im using), however it then jumps to the else statement but prints out "gps". Why is this happening?

Akshat Agarwal
  • 2,837
  • 5
  • 29
  • 49

3 Answers3

1

Your code should be as such:

String provider = loc.getProvider();

// Might want to consider a null check as well, because lol @ NullPointerExceptions
if (provider.equals(gps)) {
    // blah
} else {
    // blah
}

When you use == you're checking if one Object reference is identical to another. In this particular case, you want to check if the CONTENTS of one String is equal to another. They are two distinct Objects in the eyes of the JVM. The JVM can apply optimizations to the pool of String constants where two separate Strings with the same content are pointing to the same Object behind the scenes, but that is not the case here.

Also, I suggest putting the call into a separate variable because I notice in your code you're calling loc.getProvider() multiple times, so it's a good candidate for its own variable.

MattC
  • 12,285
  • 10
  • 54
  • 78
1

because you cannot compare strings like that

you need to do

loc.getProvider().equals(gps)
tyczj
  • 71,600
  • 54
  • 194
  • 296
1

You can't compare strings with "==" operator. Use string equality method - if (loc.getProvider().equals(gps))

Daniel Kim
  • 65
  • 6