Question

I use one in my sqlite database a config table. This has the following composition:

private static final String DATABASE_CONFIG_CREATE = 
    "CREATE TABLE " + TABLE_CONFIGS
    + "("
        + CONFIG_HIDDEN_CATEGORIES + " TEXT DEFAULT '1,2' NULL"
    + ");";

Later I try to access with the following code:

Cursor cursor = database.query(DatabaseHelper.TABLE_CONFIGS, new String[] {DatabaseHelper.CONFIG_HIDDEN_CATEGORIES}, null, null, null, null, null);
try {
    cursor.moveToFirst();

    int test = cursor.getCount();

    String data = cursor.getString(0);

}
catch (Exception exception) {

But the line cursor.getString(0) throws the following exeption (variable test is 0):

android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

when I run the following code, the column CONFIG_HIDDEN_CATEGORIES is displayed to me... what is wrong?

    Cursor dbCursor = database.query(DatabaseHelper.TABLE_CONFIGS, null, null, null, null, null, null);
    String[] columnNames = dbCursor.getColumnNames(); // index 0 is the value of CONFIG_HIDDEN_CATEGORIES
Was it helpful?

Solution

It means that your Cursor is empty. You should wrap your actions to correct condition:

try {
    if (cursor.moveToFirst()) {
       String data = cursor.getString(cursor.getColumnIndex("columnName"));
       // do your stuff
    }
    else {
       // cursor is empty
    }
}
...

Your actual code won't work correct because you just calling moveToFirst() method but you don't know (are not testing) if it'll return true or false.

Your code works correct only if Cursor is not empty. In second case it won't work.

Note: I recommend you to use getColumnIndex(<columnName>) method for getting column index due to its name. This method is safer and more human-readable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top