zoukankan      html  css  js  c++  java
  • Android 利用cursor来进行排序

    主要思路是: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 sortList = new ArrayList();
    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 comparator = new Comparator(){
    @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;
    }
    
    }
  • 相关阅读:
    Xshell相关优化
    Inotify+rsync远程实时同步
    MySQL主从复制故障解决
    Docker部署centos7容器
    Salt-ssh批量部署minion
    MySQL数据库二
    防火墙2
    MySQl数据库
    防火墙
    http原理2
  • 原文地址:https://www.cnblogs.com/vus520/p/2561879.html
Copyright © 2011-2022 走看看