java.lang.IllegalArgumentException: column '_id' does not exist

来源:互联网 发布:淘宝客怎么找佣金高的 编辑:程序博客网 时间:2024/05/29 17:09
android报错: java.lang.IllegalArgumentException: column '_id' does not exist
使用Cursor相关的Adapter时需要一个自增的列,且名字必需为 _id。
举个特殊的例子:
--创建一张SQLite的表 (字段均大写)
Create Table  Test(_ID integer primary key autoincrement,NAME text,URL text,DESC text)
// XX类中的查询方法
public Cursor query() {
   return getReadableDatabase().query("Test", new String[] { "_ID as _id", "name", "desc", "url"}, null, null, null, null, null);
}
//Activity类中的一个普通展示方法
public void showListView() {
   Cursor c = new XX().query();
   /*
   if (c.moveToFirst()) {
      for (int i = 0; i < c.getCount(); i++) {
         c.move(i);
         Map map = new HashMap();
         for (int j = 0; j < c.getColumnCount(); j++) {
           map.put(c.getColumnNames()[j], c.getString(j));
         }
         System.out.println(map);
      }
   }
   */
  String[] form = { "_id", "NAME", "URL", "DESC" };//值得注意的是,这里的_id必须小写
  int[] to = { R.id.txt0, R.id.txt1, R.id.txt2, R.id.txt3 };
  SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.row, c, form, to);
  listView.setAdapter(adapter);
}
提醒:
1. 如果创建时_ID为大写,但后面需要采用适配器SimpleCursorAdapter直接展示ListView,要注意这里的_id必须小写。
   另外String[] form = { "_id", "NAME", "URL", "DESC" };仅仅这里小写还是不够的,还要在查询时采用as将_ID转为_id,如query()方法
2. 顺便扩展下 getReadableDatabase().query("Test", new String[] { "_ID as _id", "name", "desc", "url"}, null, null, null, null, null);
   你会发现,我明明将_ID、NAME、DESC、URL均转化为小写,为何只有_id是小写
   System.out.println(map);
   打印效果格式为(前提表里有数据):
   {URL=, _id=1, DESC=, NAME=}
   {URL=2, _id=2, DESC=3, NAME=1}
   原因是,在查询是列头字段文本显示的优先级:as 【_ID as _id】 > 默认列头【_ID】 > 普通写法【_id】
欢迎评论,就当支持开源哦!