2010-08-26 48 views
10

我有一个Android应用程序,我想查看是否安装的应用程序名称与传递给包含此代码的函数的字符串匹配。代码和例子如下:为什么我的字符串比较失败?

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; 
} 

假设你叫checkInstalledApp("SetCPU");和手机上的应用程序的名字叫做它应该返回true同样的事情。但是,它从来没有。我记录了结果,它应该匹配,但它不。任何人都可以请赐教,为什么这不起作用?

回答

41

使用String的equals()方法,而不是用于比较字符串==操作符:

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

在Java中,最常见的错误满足新人使用==比较字符串之一。您必须记住,==比较了对象引用,而不是内容。

+1

我明白了。这绝对是这位新人所犯的一个错误。谢谢。 – 2010-08-26 15:15:40

5
+0

虽然这可能在理论上回答这个问题,[这将是更可取的](http://meta.stackexchange.com/q/8259)在这里包括答案的基本部分,并提供参考链接。 – 2013-06-06 13:50:14

+0

@JoachimSauer伊顿已经充分回答了这个问题,我提供了额外的信息。也许它应该是一个评论 – Blundell 2013-06-06 18:29:20

0
public static boolean compaireString (String string, String string2) 
{ 
    // string == null && String2 == null or they reference the same object 
    if (string == string2) return true; 
    //we have to be sure that string is not null before calling a methode on it 
    if (string != null && string.equals(string2)) return true; 

    return false; 
}