dythe
dythe

Reputation: 841

Sorting listview alphabetically by App name instead of package name

I am trying get this ListView working and i'm trying to sort the list alphabetically by the application name instead of the package name.

MainActivity.java

// load list application
mListAppInfo = (ListView)findViewById(R.id.lvApps);
// create new adapter
AppInfoAdapter adapter = new AppInfoAdapter(this, Utilities.getInstalledApplication(this), getPackageManager());
// set adapter to list view        
mListAppInfo.setAdapter(adapter);

AppInfoAdapter.java

public AppInfoAdapter(Context c, List list, PackageManager pm) {
    mContext = c;
    mListAppInfo = list;
    mPackManager = pm;
}

public View getView(int position, View convertView, ViewGroup parent) {
    // get the selected entry
    ApplicationInfo entry = (ApplicationInfo) mListAppInfo.get(position);

    // reference to convertView
    View v = convertView;

    // inflate new layout if null
    if(v == null) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        v = inflater.inflate(R.layout.layout_appinfo, null);
    }

    // load controls from layout resources
    ImageView ivAppIcon = (ImageView)v.findViewById(R.id.ivIcon);
    TextView tvAppName = (TextView)v.findViewById(R.id.tvName);
    TextView tvPkgName = (TextView)v.findViewById(R.id.tvPack);

    // set data to display
    ivAppIcon.setImageDrawable(entry.loadIcon(mPackManager));
    tvAppName.setText(entry.loadLabel(mPackManager));
    tvPkgName.setText(entry.packageName);

    // return view
    return v;
}

Upvotes: 1

Views: 2288

Answers (2)

icortesi
icortesi

Reputation: 760

An option to biegleux code if you are using packageManager.queryIntentActivities(intent, 0).

List<ResolveInfo> apps = packageManager.queryIntentActivities(intent, 0);
Collections.sort(apps, new ResolveInfo.DisplayNameComparator(packageManager));

Upvotes: 0

biegleux
biegleux

Reputation: 13247

Modify your Utilities.getInstalledApplication(this) to use Collections.sort():

public static List<ApplicationInfo> getInstalledApplication(Context context) {
    PackageManager packageManager = context.getPackageManager();
    List<ApplicationInfo> apps = packageManager.getInstalledApplications(0);
    Collections.sort(apps, new ApplicationInfo.DisplayNameComparator(packageManager));
    return apps;
}

Upvotes: 7

Related Questions