kirktoon1882
kirktoon1882

Reputation: 1231

Android SQlite date without a year?

In my Android app, I'm trying to retrieve a string from my database based on the date. But I don't want the year in the date (that way I only have to have 365 rows). The only way I've gotten it to work is in my DB, have the date in the Date column be in the format yyyyMMdd. If I change all the dates in the Date column to be in the format MMdd, the double digit months (like Oct, Nov, Dec) work, but the single digit months like Jan. or Sept. (01, 09) crash the app with the error CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0. I've tried the formats MM-dd, yyyy-MM-dd, in the DB and they crash the app with the error listed above. Is it not possible to have the date formatted with just MMdd in a Sqlite database? Any ideas?

MainActivity:

    DBT = new SimpleDateFormat("MMdd", Locale.US);
tMMddStr = DBT.format(new Date(System.currentTimeMillis()));

private void getTH() {

    dba.open();
    tArray = dba.getTHA(tMMddStr);
    dba.close();
    optionB_TV.setText(todayArray[2]);
    hideDayAtv.setText(todayArray[1]);
    hideYearAtv.setText(todayArray[0]);

}

DBAdapter:

    public String[] getTHA(String tMMddStr) {   
    String[] columns = new String[] { KEY_Y, KEY_MD, KEY_HA };
    Cursor cursor = db.query(DB_TABLE, columns, KEY_DATE + "=" + tMMddStr,
            null, null, null, null);

    if (cursor != null) {
        cursor.moveToFirst();
        String hapT[] = new String[3];
        hapT[0] = cursor.getString(0);
        hapT[1] = cursor.getString(1);
        hapT[2] = cursor.getString(2);
        cursor.close();
        this.db.close();
        return hapT;
    }
    return null;
}

Upvotes: 0

Views: 174

Answers (1)

Sam
Sam

Reputation: 86948

CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

This error means that you are trying to read an empty Cursor, simply check if the Cursor has any data before trying to read it:

if (cursor != null && cursor.moveToFirst()) {

As far as the single digit month problem, this could be related to the KEY_DATE column's data type. If KEY_DATE is any type of number, it will strip out the first 0. Try doing the same to tMMddStr.
(If this didn't help, post your tables CREATE statement and a few examples of how you are putting data into the database and pulling it out.)

Upvotes: 1

Related Questions