-4

I have created an app in android studio and it uses a background service which has a method which starts a counter of seconds. I have created an if statement to test if the seconds are at 0 and when i debug the value seems to be correct but the condition is jumping straight to the else statement and i can not figure out why.

  public void checkService(){
              long secs = seconds;

        String str = String.valueOf(secs);

        if(str == "0")
        {
            Toast.makeText(this, "Not started", Toast.LENGTH_SHORT).show();
        }
        else
        {
            Toast.makeText(this, "Running", Toast.LENGTH_SHORT).show();
        }
    }

It is jumping to the second esle even when the value is 0. The image shows the value of str when i was debugging.

enter image description here

James Ferry
  • 127
  • 1
  • 3
  • 12

1 Answers1

1

You should never test objects with ==. You should use .equals instead:

    if(str.equals("0"))
    {
        Toast.makeText(this, "Not started", Toast.LENGTH_SHORT).show();
    }
    else
    {
        Toast.makeText(this, "Running", Toast.LENGTH_SHORT).show();
    }

Some explanation at an answer from another post: https://stackoverflow.com/a/513839/2174489

Eduardo Herzer
  • 2,033
  • 21
  • 24
  • Brilliant thank you, I was trying something similar to that but i was putting if(str.equals(0) and obviously getting the wrong result. Thats has worked now tho thank you I will get a read over that – James Ferry Jan 31 '18 at 19:29