How to sort the <PackageInfo> list in android ..?
List<PackageInfo> pkginfoList = getPackageManager() .getInstalledPackages(0); How to sort PackageInfo , I made ApplicationInfo which works fine
Collections.sort(installedList, new ApplicationInfo.DisplayNameComparator(packageManager)); but I want to implement PackageInfo as well.
I am not sure how to do this. Please help me...!
The Collections.sort method takes two parameters:
- The list you want to sort
- And a Comparator object used to compare items whose type is the type of items in your list.
In your case, you want to implement Comparator<PackageInfo> . An example assuming PackagInfo has a getName() method:
new Comparator<PackagInfo>() { @Override public int compare(PackagInfo arg0, PackagInfo arg1) { return arg0.getName().compareTo(arg1.getName()); } }; Another solution is getting from there, but I don't know Android well. Looking at the code snippet you specified, maybe you have a static field PackageInfo.xxxx whose type is Comparator<PackageInfo> ?
Since Manuel Selvaโs answer didnโt actually work for me, here is what I did to improve it - if you want to sort the packages according to their application name:
Collections.sort(packages, new Comparator<PackageInfo>() { @Override public int compare(PackageInfo arg0, PackageInfo arg1) { CharSequence name0 = arg0.applicationInfo.loadLabel(Context.getPackageManager()); CharSequence name1 = arg1.applicationInfo.loadLabel(Context.getPackageManager()); if (name0 == null && name1 == null) { return 0; } if (name0 == null) { return -1; } if (name1 == null) { return 1; } return name0.toString().compareTo(name1.toString()); } }); I think that what you are looking for has already answered this post.
Have you tried to find existing messages with a solution before creating a new question?