-2

Possible Duplicate:
How do I compare strings in Java?

I dont understand why the the first (same for other ones) if in sendMessage never gets true. The reciever String is exactly what it should be to be true?!

When i run this and press send to Alice I get 3 Toast:

  1. Send to Alice (=value of reciever)
  2. [a blank toast] (=value of phoneNumber)
  3. You have to choose a message (=nevermind this!)

    public void onSend(View src){
    Button b = (Button)src;
    
    sendMessage(b.getText().toString());
    
    }
    
    public void sendMessage(String reciever){
    
    String phoneNumber = "";
    Toast.makeText(this, reciever, Toast.LENGTH_LONG).show();
    
    if (reciever == "Send to Alice"){
        phoneNumber = "01230340645";
        Toast.makeText(this, "hej", Toast.LENGTH_LONG).show();
    }
    
    else if (reciever == "Send to Bob"){
        phoneNumber = "020312039";
    }
    
    else if (reciever == "Send to John"){
        phoneNumber = "0102308013";
    }
    
    Toast.makeText(this, phoneNumber, Toast.LENGTH_LONG).show();
    
    if (_message == ""){
        Toast.makeText(this, "You have to choose a message!", Toast.LENGTH_LONG).show();
    } else {
        Intent sms = new Intent(Intent.ACTION_SENDTO, Uri.parse("sms:" + phoneNumber));
        sms.putExtra("sms_body", _message);
        startActivity(sms);
        _message = "";
    }
    
     }
    
Community
  • 1
  • 1
tobbe
  • 1,737
  • 6
  • 23
  • 40

3 Answers3

11

Don't use == to compare Strings in Java. Use the equals method.

if (reciever.equals("Send to Alice"))...

The == operator compares references for equality, not the objects those references point to.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
5

try this....

From:

if (reciever == "Send to Alice")

To:

if (receiver.equals("Send to Alice"))
David M
  • 2,511
  • 1
  • 15
  • 18
1
if (receiver.equals("Send to Alice"))

if that "Send to Alice" is to be checked with case sensitivity and

if (receiver.equalsIgnoreCase("Send to Alice"))

if that "Send to Alice" is to be checked without case sensitivity and

because == will check only the integers(similar) and for strings .equals should be used

VIGNESH
  • 2,023
  • 8
  • 31
  • 46