android - CursorIndexOutOfBoundsException thrown by cursor.getString() -


i use 1 in sqlite database config table. has following composition:

private static final string database_config_create =      "create table " + table_configs     + "("         + config_hidden_categories + " text default '1,2' null"     + ");"; 

later try access 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 line cursor.getstring(0) throws following exeption (variable test 0):

android.database.cursorindexoutofboundsexception: index 0 requested, size of 0

when run following code, column config_hidden_categories displayed me... wrong?

    cursor dbcursor = database.query(databasehelper.table_configs, null, null, null, null, null, null);     string[] columnnames = dbcursor.getcolumnnames(); // index 0 value of config_hidden_categories 

it means cursor empty. should wrap actions correct condition:

try {     if (cursor.movetofirst()) {        string data = cursor.getstring(cursor.getcolumnindex("columnname"));        // stuff     }     else {        // cursor empty     } } ... 

your actual code won't work correct because calling movetofirst() method don't know (are not testing) if it'll return true or false.

your code works correct if cursor not empty. in second case won't work.

note: recommend use getcolumnindex(<columnname>) method getting column index due name. method safer , more human-readable.


Comments