【问题标题】:Sort alphabetically listview populated from cursor按字母顺序排序从光标填充的列表视图
【发布时间】:2017-12-16 22:58:03
【问题描述】:

我有一个从使用适配器显示的光标获取的 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);
    }
}

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

【问题讨论】:

  • 为什么不编写返回排序结果的查询?
  • ok 我将如何使查询刷新当前将数据填充到列表视图的游标,例如此方法 fethSortedData() 返回排序结果游标我将如何使用当前游标更改它菜单点击

标签: android arrays sorting colors


【解决方案1】:

用户列表示例。

创建一个比较器:

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() {});

【讨论】:

  • 我使用的是游标而不是 Arraylist,它本来可以直接使用 ArrayList
  • 你不在 RecyclerView 中使用 List 或 ArrayList 吗?
  • 不,我将光标传递给适配器并获取 cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_SCIENTIFICNAME));像这样的价值观
【解决方案2】:

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

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

【讨论】:

  • 这个sort()从哪里来的
  • 查看 Sigma 的回复。如果你创建一个自定义对象,你必须决定它是如何排序的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-15
  • 2015-05-04
  • 1970-01-01
  • 1970-01-01
  • 2013-04-01
  • 2021-02-03
相关资源
最近更新 更多