我设计了一个数据库。这是我的代码:
Cursor cursor =database.query(ColumnID.AGENT_TABLE,null,null,null,null,null,null);
while (cursor.moveToNext()) {
County county = new County();
county.setId(cursor.getString(cursor
.getColumnIndex(ColumnID.ID)));
county.setAgent_Name(cursor.getString(cursor
.getColumnIndex(ColumnID.AGENT_NAME)));
county.setAddress_Line_1(cursor.getString(cursor
.getColumnIndex(ColumnID.ADDRESS_LINE_1)));
countyList.add(county);
}
不幸的是,我收到了这个错误:
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
答案 0 :(得分:1)
Cursor cursor =database.query(ColumnID.AGENT_TABLE,null,null,null,null,null,null);
if (cursor.getCount() > 0)
{
cursor.moveToFirst();
while (!cursor.isAfterLast())
{
County county = new County();
county.setId(cursor.getString(cursor
.getColumnIndex(ColumnID.ID)));
county.setAgent_Name(cursor.getString(cursor
.getColumnIndex(ColumnID.AGENT_NAME)));
county.setAddress_Line_1(cursor.getString(cursor
.getColumnIndex(ColumnID.ADDRESS_LINE_1)));
countyList.add(county);
cursor.moveToNext();
}
}
答案 1 :(得分:0)
我不确定你是否收到错误,因为数据表中没有记录而你试图在空集上移动ToNext(),或者是因为你正在访问查询结果不在那里。
如果是前者:错误似乎是因为游标中没有记录,当你尝试moveToNext()时,记录不存在。它是SQLite版本的空指针异常(排序)。
相反,请尝试:
Cursor cursor =database.rawQuery("SELECT * FROM " + ColumnID.AGENT_TABLE);
cursor.moveToFirst();
//this checks to make sure you don't have an empty set
if(!cursor.isAfterLast())
{
do{
County county = new County();
county.setId(cursor.getString(cursor
.getColumnIndex(ColumnID.ID)));
county.setAgent_Name(cursor.getString(cursor
.getColumnIndex(ColumnID.AGENT_NAME)));
county.setAddress_Line_1(cursor.getString(cursor
.getColumnIndex(ColumnID.ADDRESS_LINE_1)));
countyList.add(county);
}while(cursor.moveToNext());
} else{
Log.v("MyTag", "There are no countries in the data set");
}