Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my String to String comparison failing?

I have an Android app where I want to check to see if an app name that is installed matches a string passed to the function containing this code. The code and example is below:

private Boolean checkInstalledApp(String appName){
    PackageManager pm = this.getPackageManager(); 
    Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); 
    mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); 
    List<ResolveInfo> list = pm.queryIntentActivities(mainIntent, 0);
    Boolean isInstalled = false;
    for(ResolveInfo info: list) {
      if (info.activityInfo.applicationInfo.loadLabel( pm ).toString()==appName){
          isInstalled = true;
          break;  
      }
    } 

    return isInstalled;
}

Assuming you called checkInstalledApp("SetCPU"); and the app name on the phone is called the same thing it should return true. However, it never does. I logged the results and it should match up but it does not. Can anyone please enlighten me as to why this doesn't work?

like image 858
Chuck Hriczko Avatar asked Aug 26 '10 14:08

Chuck Hriczko


People also ask

Why == does not work with string?

You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.

Do you use == or .equals for string?

Unfortunately, it's easy to accidentally use == to compare strings, but it will not work reliably. Remember: use equals() to compare strings. There is a variant of equals() called equalsIgnoreCase() that compares two strings, ignoring uppercase/lowercase differences.

How do you compare strings correctly?

The right way of comparing String in Java is to either use equals(), equalsIgnoreCase(), or compareTo() method. You should use equals() method to check if two String contains exactly same characters in same order. It returns true if two String are equal or false if unequal.

Do the comparison operators work on strings?

The comparison operators also work on strings. To see if two strings are equal you simply write a boolean expression using the equality operator.


2 Answers

Use the String's equals() method instead of the == operator for comparing strings:

info.activityInfo.applicationInfo.loadLabel( pm ).toString().equals(appName)

In Java, one of the most common mistakes newcomers meet is using == to compare Strings. You have to remember, == compares the object references, not the content.

like image 197
Eton B. Avatar answered Oct 02 '22 23:10

Eton B.


Check out number 7: Top 10 - New Java Developer Errors

like image 23
Blundell Avatar answered Oct 03 '22 01:10

Blundell