dimanche 28 février 2016

Similar SQLite toString() functions yielding different results?

I have a SQLite table initialised as such. It is a single row implementation.

public void onCreate(SQLiteDatabase db) {
    String query = "CREATE TABLE " + TABLE_PRODUCTS + "(" +
            COLUMN_ID + " INTEGER PRIMARY KEY DEFAULT 1, " +
            COLUMN_PRODUCTNAME + " TEXT ," +
            COLUMN_DATE + " TEXT " +
            ");";
    db.execSQL(query);
}

I update the row this way.

public void updateRow(int id, Products product){
    ContentValues values = new ContentValues();

    values.put(COLUMN_ID, id);
    values.put(COLUMN_PRODUCTNAME, product.get_productname());
    values.put(COLUMN_DATE, getDateTime());

    SQLiteDatabase db = getWritableDatabase();
    db.replace(TABLE_PRODUCTS, null, values);
    db.close();
}

Initially, I did not have COLUMN_DATE. I tacked it on after the original was working correctly. When I want to check that things work, I toast a String to the screen. And this works great with COLUMN_PRODUCTNAME, here's the function to do this.

public String prodToString(){
    String dbString = "";
    SQLiteDatabase db = getWritableDatabase();
    String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
    Cursor c = db.rawQuery(query, null);
    c.moveToFirst();
    dbString = c.getString(c.getColumnIndex(COLUMN_PRODUCTNAME));
    db.close();
    return dbString;
}

But when I copypasted the exact same function above under name dateToString(), only changing COLUMN_PRODUCTNAME to COLUMN_DATE and call said function, I get the error:

Failed to read row 0, column -1 from a CursorWindow which has 1 rows, 2 columns.

java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. 

Make sure the Cursor is initialized correctly before accessing data from it.

I doubt it has anything to do with the getDateTime() function, because I can output that fine. Whether I put it into the table correctly is still unclear to me, but it looks to be ok in that sense. I'm not sure what's going wrong. Can anyone see it?

Aucun commentaire:

Enregistrer un commentaire