首页 > 代码库 > Android 利用cursor来进行排序(转至http://blog.csdn.net/yangzongquan/article/details/6547860)
Android 利用cursor来进行排序(转至http://blog.csdn.net/yangzongquan/article/details/6547860)
主要思路是:override move系列的方法,让cursor以自己想要的顺序来移动,从而达到对cursor排序的目的。比如数组A0里有 4(0),3(1),1(2),2(3),括号内为位置,排序后用数据记录A1:1(2),2(3),3(1),4(0)。要访问第一个元素,则访问 A1[0]得到1(2),根据(2)找到在A0中的实际位置2,即1(2)。参考了下系统的CursorWrapper和AbstractCursor代 码实现,另外有时间可以顺带了解下MatrixCursor。
package com.xx.test; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import android.database.Cursor; import android.database.CursorWrapper; import com.xx.test.SortCursor.SortEntry; public class SortCursor extends CursorWrapper implements Comparator<SortEntry>{ public SortCursor(Cursor cursor) { super(cursor); } Cursor mCursor; ArrayList<SortEntry> sortList = new ArrayList<SortEntry>(); int mPos = 0; public static class SortEntry { public String key; public int order; } public int compare(SortEntry entry1, SortEntry entry2) { return entry1.key.compareTo(entry2.key); } public SortCursor(Cursor cursor, String columnName) { super(cursor); mCursor = cursor; if (mCursor != null && mCursor.getCount() > 0) { int i = 0; int column = cursor.getColumnIndexOrThrow(columnName); for (mCursor.moveToFirst(); !mCursor.isAfterLast(); mCursor.moveToNext(), i++) { SortEntry sortKey = new SortEntry(); sortKey.key = cursor.getString(column); sortKey.order = i; sortList.add(sortKey); } } Collections.sort(sortList, this); } public boolean moveToPosition(int position) { if (position >= 0 && position < sortList.size()) { mPos = position; int order = sortList.get(position).order; return mCursor.moveToPosition(order); } if (position < 0) { mPos = -1; } if (position >= sortList.size()) { mPos = sortList.size(); } return mCursor.moveToPosition(position); } public boolean moveToFirst() { return moveToPosition(0); } public boolean moveToLast() { return moveToPosition(getCount() - 1); } public boolean moveToNext() { return moveToPosition(mPos + 1); } public boolean moveToPrevious() { return moveToPosition(mPos - 1); } public boolean move(int offset) { return moveToPosition(mPos + offset); } public int getPosition() { return mPos; } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。