tags:

views:

96

answers:

3

Ok so 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?

+8  A: 

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.

Eton B.
Ah I see. That is definitely a mistake this newcomer made. Thanks.
Chuck Hriczko
+1  A: 

Read up on Java String Comparison

fredley
Doing == with Strings compares objects, i.e. two strings with identical values are still different objects, leading to misleading results.
fredley
A: 

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

Blundell