【问题标题】:CursorAdapter bindView disorderCursorAdapter bindView 乱序
【发布时间】:2013-08-19 20:44:56
【问题描述】:

我正在尝试使用 Cursor 和 Loader 从 SQliteDatabase 填充 ListView,但所有项目都显示完全无序

我的 CursorAdapter 类

@Override
public void bindView(View view, Context context, Cursor c) {
    ItemHolder holder = null;
    try{
        holder = (ItemHolder) view.getTag();
    } catch (Exception e){
        e.printStackTrace();
    }

    if(holder != null){
        System.out.println("b "+holder.position);
    }

}

@Override
public View newView(Context context, Cursor c, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View nView = inflater.inflate(layoutID, parent, false);

    ItemHolder holder = new ItemHolder();
    System.out.println("a "+c.getPosition());
    holder.position = c.getPosition();
    nView.setTag(holder);

    return nView;
}

单次完整滚动返回后的 Logcat 输出(a 是 newView() 中的位置,b 是 bindView() 中的位置)

a 0
b 0
a 1
b 1
a 2
b 2
b 0

而不是

a 0
b 0
a 1
b 1
a 2
b 2
a 3
b 3

在适配器中检查光标返回正确的数据

c.moveToFirst();
    for(int i = 0; i < c.getCount(); i++){
        System.out.println(i+" "+c.getString(c.getColumnIndex(COL_NAME)));
        c.moveToNext();
    }

我使用最新的 anroid.support.v4 库

【问题讨论】:

    标签: android listview android-cursoradapter


    【解决方案1】:

    您需要在 SQL 语句中添加一个ORDER BY 子句,用于对查询结果进行排序。查看the documentationthis example 了解更多详情。

    示例:

    SELECT * FROM <table> ORDER BY <column>;
    

    p.s.:如果您使用的是database.query(...),您可以在此处为排序列添加参数(参见orderBy):

    query(String table, String[] columns, String selection, 
          String[] selectionArgs, String groupBy, String having, String orderBy) 
    

    查看Android documentation

    【讨论】:

      猜你喜欢
      • 2012-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 2012-06-05
      • 1970-01-01
      • 1970-01-01
      • 2012-09-22
      相关资源
      最近更新 更多