Android Cursor initialization [duplicate]

余生长醉 提交于 2021-02-07 10:50:07

问题


I have designed a database. Here is my code:

  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);
        }

Unfortunately, I'm getting this error:

 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.

Reference: Android Cursor initialization


回答1:


I'm not sure if you're getting the error because there are no records in the datatable and you're trying to moveToNext() on an empty set, or if it is because you are accessing the query for results that aren't there.

If its the former: The error seems to be because there are no records in the cursor, when you try to moveToNext() the record doesn't exist. Its the SQLite version of a null pointer exception (sort of).

Instead, try:

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");
}



回答2:


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();
    }
}


来源:https://stackoverflow.com/questions/37050574/android-cursor-initialization

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!