1. Download our Official Android App: Forums for Android!

Apps Error when comparing to strings

Discussion in 'Android Development' started by tellblom, Jun 29, 2010.

  1. tellblom

    tellblom Lurker
    Thread Starter
    Rank:
    None
    Points:
    5
    Posts:
    2
    Joined:
    Jun 29, 2010

    Jun 29, 2010
    2
    0
    5
    I have this code in my app

    Ver = "1.5.2"
    VersionsKoll = "1.5.2"

    if (VersionsKoll == Ver)
    {
    //Do something
    }​

    This gets the result "false"​

    When I debug I get this in the watchwindow:
    http://www.tellblom.se/android/strings.jpg

    Can someone explain this to me?
    /M​
     

    Advertisement

  2. markb

    markb Well-Known Member
    Rank:
    None
    Points:
    63
    Posts:
    148
    Joined:
    Sep 14, 2009

    Sep 14, 2009
    148
    26
    63
    Software Developer (Java, C, Web, Unix)
    Birmingham, UK
    Hi tellblom,

    Your code is behaving correctly as Ver and VersionsKoll are different objects, and == tests to see if two variables refer to the same object. It doesn't check if the two objects have the same value. In C/C++ terms it's like comparing two pointers to see if they have the same address, rather than checking to see if they point to data that looks the same.

    To compare strings you need to use the "equals" method on one of the strings.

    Code (Text):
    1. if ( VersionKoll.equals(Ver) )
    2. {
    3.  . . . they match . . .
    4. }
    5.  
    In general, if the string could be null, then you'd write something like this instead, so you don't call a method on a null object:

    Code (Text):
    1. if ( VersionKoll != null && VersionKoll.equals(Ver) )
    2. {
    3.  . . . they match . . .
    4. }
    5.  
    See this page for more information:

    Comparing Strings and Portions of Strings (The Java
     
    tellblom likes this.
  3. tellblom

    tellblom Lurker
    Thread Starter
    Rank:
    None
    Points:
    5
    Posts:
    2
    Joined:
    Jun 29, 2010

    Jun 29, 2010
    2
    0
    5
    Thanx alot,

    As you proberbly understand I usually code in C# and the quite similar to java.

    Once again thanx for this.

    /M
     

Share This Page

Loading...