2010-08-26 72 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; 
}