mardi 31 mars 2015

Android SqLite Cursor.getgetColumnIndex() Doesn't seem o be working

I'm quite desperate here and can't figure out if there is a bug in my code or if i've done something wrong. My Problem is in reading a database which stores images as Blobs. I have followed tutorials to implement this but something seems broken.


First of i created a databaseHelper class that creates my databases.



@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TBLE_PROFILEIMG + " (" +
FLD_ALLTABLES_UNIQUEPICID + " INTEGER, " +
FLD_ALLTABLES_DELETABLE + " BOOLEAN, " +
FLD_ALLTABLES_PICTURE + " BLOB);");
db.execSQL("CREATE TABLE " + TBLE_EXIMG + " (" +
FLD_EXERCISE_ID + " TEXT, " +
FLD_ALLTABLES_DELETABLE + " BOOLEAN, " +
FLD_ALLTABLES_UNIQUEPICID + " INTEGER, " +
FLD_ALLTABLES_PICTURE + " BLOB);");

}


Then i Created a class to write to the database, There is no problem here and i am sure everything works on spot because i pulled the database from my device and opened it with SQLite Studio. The fields are created correctly and images successfully written as BLOB from an array of bytes.



public List<MyPicture> getProfilePictures() {
Cursor c = readTable(ImgDatabaseHelper.TBLE_PROFILEIMG);
List<MyPicture> bl = new ArrayList<>();
if (c.moveToFirst()) {
while (true) {
int colidx = c.getColumnIndex(ImgDatabaseHelper.FLD_ALLTABLES_PICTURE);
byte[] bb = c.getBlob(colidx);
Bitmap pic = BitmapFactory.decodeByteArray(bb, 0, bb.length);
if (pic != null)
bl.add(
new MyPicture(
pic,
c.getInt(c.getColumnIndex(ImgDatabaseHelper.FLD_ALLTABLES_UNIQUEPICID)),
c.getInt(c.getColumnIndex(ImgDatabaseHelper.FLD_ALLTABLES_DELETABLE)) > 0
)
);

if (c.isLast()) break;
else c.moveToNext();
}
}
return bl;
}


It Can't find the Column:



E/CursorWindow﹕ Failed to read row 0, column 2 from a CursorWindow which has 0 rows, 3 columns.


The Column surely exists because i verified it in sqlite studio. and the column index keeps coming back as null. I am guessing my problem is in the query because the exception says that there are 0 rows when infact i verified that there are 4 rows present. Here is my readTable method:



private Cursor readTable(String table) {
Cursor crs = null;
try {
// Has the same result as the statment under it
// crs = db.query(table, null, null, null, null, null, null, null);
crs = db.rawQuery("SELECT * FROM " + table, null);
}
catch(SQLiteException e) { }
return crs;
}

Aucun commentaire:

Enregistrer un commentaire