Android SQLite 数据库 java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow异常

有时候很小的一个马虎,就会导致很多错误。近来在做项目的时候,遇到如下异常:


java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.


插入数据库的操作如下:

ContentResolver resolver = mActivity.getContentResolver();
ContentValues values = new ContentValues();
String extInfo = "sth";
values.put(MyContract.EXT_INFO, extInfo);
resolver.insert(MyContract.MSG_URI, values);

查询数据库的操作如下:

Cursor cursor = mService.getContentResolver().query(MyContract.MSG_URI, null, MyContract.MSG_ID + "=?", new String[] { msgId }, null);
String extInfo = cursor.getString(cursor.getColumnIndex(MyContract.EXT_INFO));

此时会报错,问题出现在这一行:

cursor.getColumnIndex(MyContract.EXT_INFO)


经过debug后发现,
cursor.getColumnIndex(MyContract.EXT_INFO)
返回的值是-1,即没找到这个字段。


经过分析,发现MyContract.EXT_INFO的值是

public static final  String EXT_INFO ="ext_info ";
这里多了一个空格,所以导致插入数据库的时候没问题,查询数据库的时候找不到。我想这应该是Android的一个bug,即插入操作是按照变量EXT_INFO的字段名(包含一个空格)插入的,调用getColumnIndex(MyContract.EXT_INFO)方法的时候去掉了变量EXT_INFO的空格。


你可能感兴趣的:(Android,Debug)