android小问题-------------SimpleCursorAdapter使用时的问题。 java.lang.IllegalArgumentException: column '_id' d

来源:互联网 发布:linux cp -f 编辑:程序博客网 时间:2024/04/29 01:22

SimpleCursorAdapter使用时报错误:java.lang.IllegalArgumentException: column '_id'does not exist

SimpleCursorAdapter adapter.notifyDataSetChanged()更新视图不起作用。大笑

---------------------------------------------------------

在使用SQLIteOpenHelper和SQLiteDatebase不免要使用到方便的Cursor适配器SimpleCursorAdapter,但是使用这个适配器的时候,就会发生如下错误,

解决column'_id'does not exist

自学者有时候把所有代码都核对一次都没问题可是到这就说找不到这一列确实不知道怎么办了。其实这是SimpleCursorAdapter的特殊之处。SimpleCursorAdapter要求填入的Cursor必须有_id这一列,并且还是自增的,真是太奇葩了。。。知道了原因就容易解决问题了,两个方法:

1:改变表结构,添加一列_id列,并且为自增的。

2::如果原来有类似功能的列,比如主键 id ,那么查询出来后,将id设置为_id即可,比如select id as _id from table.


第二个问题:

SimpleCursorAdapter想要通过notifyDataSetChanged方法来更新数据。必须在之前调用如下两个方法之一:

adapter.swapCursor(newCursor);
adapter.changeCursor(newCursor);
参数为新查询的Cursor对象。那么这两个方法又是什么关系?看源码:

1 public void changeCursor(Cursor cursor) {2         Cursor old = swapCursor(cursor);3         if (old != null) {4             old.close();5         }6     }
说明changeCursor()方法实际是调用swapCursor方法,区别就是,sqapCursor方法更新完Cursor对象之后,没有将旧的Cursor关闭,changeCursor中将其关闭了。




0 0
原创粉丝点击