按字母顺序排序从光标填充的listview

时间:2017-07-12 13:24:30

标签: android arrays sorting colors

我有一个列表视图,其中填充了一个带有光标的sqlite数据,该光标与适配器一起显示,我想在操作栏菜单上单击列表视图,但光标似乎不像数组列表那样直接。

将接收游标对象片段并传递给onCreate()

中的适配器
 databaseManager = new DatabaseManager(this);
    databaseManager.open();

    cursor = databaseManager.queryAllInsects();
    swapCursor(cursor);
    mAdapter = new InsectRecyclerAdapter(this, cursor);
    bugsInsectRecyclerview.setAdapter(mAdapter);

在optionsItemSelected()中,将调用菜单栏以触发刷新和排序。

 @Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

        case R.id.menu_sort_by_name:
           // WHERE SORTING WOULD BE TRIGGERED tried querying the database again an passing sort order to a cursor seems not working
            Cursor cursor2 = databaseManager.queryAllInsects(BugsContract.BugsEntry.COLUMN_FRIENDLYNAME);
            swapCursor(cursor2);
            return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}

如何按字母顺序对从光标填充的列表视图进行排序?

2 个答案:

答案 0 :(得分:0)

包含用户列表的示例。

创建一个比较器:

public class NameComparator implements Comparator<User> {

    @Override
    public int compare(User x, User y) {
        if (x == null) {
            if (y != null) return -1;
        }
        if (y == null) return 1;

        int startComparison = x.getFirstName().compareTo(y.getFirstName());
        if (startComparison == 0)
            startComparison = x.getLastName().compareTo(y.getLastName());
        return startComparison;
    }
}

然后使用它:

    Collections.sort(userList, new NameComparator() {});

答案 1 :(得分:0)

尝试在适配器内对ArrayList进行排序,然后调用notifyDataSetChanged()。如果数据没有改变,您可以在将适配器分配给适配器之前对提供的数据进行排序

cursor.sort();
mAdapter = new InsectRecyclerAdapter(this, cursor);