SimpleCursorAdapter参数from必须包含_id字段的原因

       
     String [] from ={Books.Id,Books.Name,Books.Author,Books.Category}; int [] to={R.id.ID,R.id.nameID,R.id.authorID,R.id.categoryID}; ListAdapter bookAdapter = new SimpleCursorAdapter(this,R.layout.booklist,cursor,from,to);
调试的时候在SimpleCursorAdapter出现no resource错误,起初很纳闷,就在网上搜SimpleCursorAdapter相关的错误,
网上提到,impleCursorAdapter绑定数据时,cursor必须包含一个叫"_id"的字段,否则将无法完成数据绑定。

后来就把表特定加了个_id字段,具体如下:
sqlite> alter table Books add column _id int;
代码修改后,如下:
        String [] from ={Books._Id,Books.Name,Books.Author,Books.Category};---->这里添加来_id字段
        int [] to={R.id.ID,R.id.nameID,R.id.authorID,R.id.categoryID};
        ListAdapter bookAdapter = new SimpleCursorAdapter(this,R.layout.booklist,cursor,from,to);
数据立马显示出来,神奇!

下面让我一起看看神奇的原因:

java.lang.Object
        android.widget.BaseAdapter
            android.widget.CursorAdapter
                android.widget.ResourceCursorAdapter
                    android.widget.SimpleCursorAdapter
SimpleCursorAdapter的父类android.widget.CursorAdapter有下面一段描述:
public abstract class CursorAdapter extends BaseAdapter  implements Filterable
  Adapter that  data from a Cursor to a ListView widget. The Cursor must include a column named "_id" or this class will not work.
适配游标数据大ListVIew控件时,游标数据的列必须包含"_id"列,否则这个适配类就罢工来!

所以SimpleCursorAdapter(Context context, int layout, Curso cursor, String[] from, int[] to)
函数中的from参数必须要有一个名为"_id"的对应列才能适配数据成功


 

posted @ 2014-06-17 21:37  lyyh.victory  阅读(1175)  评论(0编辑  收藏  举报