Reputation: 1400
I am getting this error when trying to read from the SQLite DB
IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
DbHelper dbHelper = new DbHelper(this);
SQLiteDatabase database = dbHelper.getWritableDatabase();
Cursor cursor = dbHelper.readNumber(database);
String ItemId;
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
//getting the ERROR here
ItemId = cursor.getString(cursor.getColumnIndex(DbContract.ITEMID));
number = cursor.getString(cursor.getColumnIndex(DbContract.PHONE_NUMBER));
callType = cursor.getString(cursor.getColumnIndex(DbContract.CALL_TYPE));
callDate = cursor.getString(cursor.getColumnIndex(DbContract.CALL_DATE));
callDuration = cursor.getString(cursor.getColumnIndex(DbContract.CALL_DURATION));
arrayList.add(new PhNumber(ItemId, number, callType, callDate, callDuration));
if (debug) {
Log.i(TAG, "DATA FOUND IN DB:\n" + "\t ID: " + ItemId + ", Number: " + number + "\n");
}
}
cursor.close();
dbHelper.close();
result = true;
if (debug) {
Log.d(TAG, " Number of items in DB: " + arrayList.size());
}
}
readNumber
public Cursor readNumber(SQLiteDatabase database) {
String[] projections = {"id", DbContract.PHONE_NUMBER};
return (database.query(DbContract.TABLE_NAME, projections, null, null, null, null, null));
}
This is my DB
private static final String CREATE = "create table " + DbContract.TABLE_NAME +
"(id integer primary key autoincrement,"
+ DbContract.ITEMID + " text, "
+ DbContract.PHONE_NUMBER + " text, "
+ DbContract.CALL_TYPE + " text, "
+ DbContract.CALL_DATE + " text, "
+ DbContract.CALL_DURATION + " text, "
+ DbContract.SYNC_STATUS + " text)";
Upvotes: 1
Views: 114
Reputation: 1400
Found the issue: I was trying to access the columns that were not added in the projects in readNumber method adding those projections solved the issue.
readNumber
public Cursor readNumber(SQLiteDatabase database) {
String[] projections = {
DbContract.ITEMID,
DbContract.PHONE_NUMBER,
DbContract.CALL_TYPE,
DbContract.CALL_DATE,
DbContract.CALL_DURATION};
return (database.query(DbContract.TABLE_NAME, projections, null, null, null, null, null));
}
Upvotes: 0
Reputation: 13272
In your projection, created by readNumber
call, you have only the id
and PHONE_NUMBER
columns returned. Probably DbContract.ITEMID
is not equal to id
and when trying to lookup the DbContract.ITEMID
in the cursor it is not found. To fix this you need to use ITEMID
in readNumber
method, something like:
public Cursor readNumber(SQLiteDatabase database) {
String[] projections = {DbContract.ITEMID, DbContract.PHONE_NUMBER};
return (database.query(DbContract.TABLE_NAME, projections, null, null, null, null, null));
}
Another issue is that you are trying to access other fields too, like: CALL_TYPE
, CALL_DATE
, etc.
So, in order to fix the issue you either:
Upvotes: 2