转自 http://jamking.iteye.com/blog/1019303
android下面需要对数据库某列的内容,按照中文拼音的顺序来排序。
baidu了下,发现常见的方式是要在数据库增加一列来存放拼音,专门用该列来排序,比如联系人就是用此方式实现的。
换google,发现有邮件中说,可以实现CursorWrapper,来达到排序功能。
具体看 How to do sorting on cursor?
http://groups.google.com/group/android-developers/browse_thread/thread/f1fc3e0fc87a3fc6
主要思路是: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
直接上代码
import java.text.Collator; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import android.database.Cursor; import android.database.CursorWrapper; public class SortCursor extends CursorWrapper{ Cursor mCursor; ArrayList<SortEntry> sortList = new ArrayList<SortEntry>(); int mPos = 0; public class SortEntry { public String key; public int order; } //直接初始化,加快比较速度,在G3上从3s->0.2s @SuppressWarnings("rawtypes") private Comparator cmp = Collator.getInstance(java.util.Locale.CHINA); @SuppressWarnings("unchecked") public Comparator<SortEntry> comparator = new Comparator<SortEntry>(){ @Override public int compare(SortEntry entry1, SortEntry entry2) { return cmp.compare(entry1.key, entry2.key); } }; public SortCursor(Cursor cursor,String columnName) { super(cursor); MusicLog.i("MediaScanner", "start-----------"); // TODO Auto-generated constructor stub 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); } } MusicLog.i("MediaScanner", "start1-----------"); //排序 Collections.sort(sortList,comparator); MusicLog.i("MediaScanner", "start2-----------"); } 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; } }