Skip to content

Instantly share code, notes, and snippets.

@emil10001
Last active August 29, 2015 13:56
Show Gist options
  • Save emil10001/9265026 to your computer and use it in GitHub Desktop.
Save emil10001/9265026 to your computer and use it in GitHub Desktop.
Compare Android ApplicationInfo so that collections of them can be sorted
public static class ApplicationInfoComparer implements Comparator<ApplicationInfo> {
private PackageManager pm1;
ApplicationInfoComparer(PackageManager pm) {
pm1 = pm;
}
@Override
public int compare(ApplicationInfo x, ApplicationInfo y) {
if (null == pm1)
return 0;
if (null == x || null == x.loadLabel(pm1))
return -1;
if (null == y || null == y.loadLabel(pm1))
return 1;
try {
return compare(x.loadLabel(pm1).toString(), y.loadLabel(pm1).toString());
} catch (NullPointerException ex) {
return 0;
}
}
// Compares two strings lexicographically. Returns an integer indicating whether this string is greater than (result is > 0),
// equal to (result is = 0), or less than (result is < 0) the argument.
private static int compare(String a, String b) {
return a.compareTo(b);
}
}
// get list of installed applications
List<ApplicationInfo> list_user_app = pm1.getInstalledApplications(0);
// sort the list using the comparer
Collections.sort(list_user_app, new ApplicationInfoComparer(pm1));
// list_user_app is now sorted
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment