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?
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.
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.
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.
The comparison operators also work on strings. To see if two strings are equal you simply write a boolean expression using the equality operator.
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.
Check out number 7: Top 10 - New Java Developer Errors
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With