Search code examples
javaandroidsqliteandroid-cursor

Error when trying to use cursor to get integer values from SQLite in Android


I'm trying to get integer values, to be displayed in a listview from SQLlite using cursors but it shows the following error:

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

Here are my code

MyItems.java:

public  ArrayList<SalesItemInformationLV> retrieveAllForlist(Context c)
{
    ArrayList<SalesItemInformationLV> items = new ArrayList<SalesItemInformationLV>();

    Cursor myCursor;
    String mystring = "";

    MyDbAdapter db = new MyDbAdapter(c);
    db.open();
    //contactIdList.clear();
    //contactList.clear();
    myCursor = db.retrieveAllEntriesCursor();

    if (myCursor != null && myCursor.getCount() > 0)
    {
        myCursor.moveToFirst();
        do {
            contactIdList.add(myCursor.getInt(db.COLUMN_KEY_ID));
            items.add(new SalesItemInformationLV(myCursor.getString(db.COLUMN_NAME_ID), myCursor.getInt(db.COLUMN_QTYSOLD_ID)));
        } while (myCursor.moveToNext());
    }
    db.close();

    return items;
}

MyDbAdapter.java:

private SQLiteDatabase _db;
private final Context context;

public static final String KEY_ID = "_id";
public static final int COLUMN_KEY_ID = 0;
public static final String ENTRY_NAME = "entry_name";
public static final int COLUMN_NAME_ID = 1;
public static final String ENTRY_QTYSOLD = "entry_qtysold";
public static final int COLUMN_QTYSOLD_ID = 4;

private MyDBOpenHelper dbHelper;
//private MyDBOpenHelper dbHelper2;

public MyDbAdapter(Context _context)
{
    this.context = _context;
    
    //step 16 - create MyDBOpenHelper object
    //constructor
    dbHelper = new MyDBOpenHelper(context, DATABASE_NAMEA, null, DATABASE_VERSION);
    //constructor
    //dbHelper2 = new MyDBOpenHelper(context, DATABASE_NAME2, null, DATABASE_VERSION);
}

public Cursor retrieveAllEntriesCursor() {
    //step 21 - retrieve all records from table
    Cursor c = null;
    try {
        c = _db.query(DATABASE_TABLE, new String[] {KEY_ID, ENTRY_NAME}, null, null, null, null, null);

    }
    catch (SQLiteException e)
    {
        Log.w(MYDBADAPTER_LOG_CAT, "Retrieve fail!");
    }

    return c;
}

I suspect the error comes from MyItems.java, but I'm having a hard time figuring out what's the error.


Solution

  • Seems like you are fetching only 2 columns(KEY_ID, ENTRY_NAME) from database and while reading you are expecting 3 columns.

     c = _db.query(DATABASE_TABLE, new String[] {KEY_ID, ENTRY_NAME}, null, null, null, null, null);
    

    You are trying to get value from column 4, which is throuing an error.

    public static final int COLUMN_QTYSOLD_ID = 4;