0

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

Community
  • 1
  • 1
Raseem Ayatt
  • 970
  • 10
  • 14
  • There's [quite a lot of similar questions here](https://stackoverflow.com/search?q=Make+sure+the+Cursor+is+initialized+correctly+before+accessing+data+from+it). – halfer May 05 '16 at 12:26
  • Please post your full code @Raseem Ayatt – Lips_coder May 05 '16 at 13:30

2 Answers2

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();
    }
}
Bhavin Kevadiya
  • 224
  • 3
  • 16
0

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");
}
Nick
  • 766
  • 4
  • 12