Search code examples
androidarraysdatabasesqlitecursor

Sqlite : ArrayIndexOutOfBoundsException when try to fetch array from database


i have create a table in sqlite that giving me java.lang.ArrayIndexOutOfBoundsException here is code while returning the array value.

    Cursor res = database.rawQuery("select "+QsDatabaseHelper.getItemName()+" from " + QsDatabaseHelper.getItemTableName(), null);
    String[] array = new String[res.getCount()];
    int i = 0;
    while(res.moveToNext()){
        String itemName = res.getString(res.getColumnIndex( QsDatabaseHelper.getItemName()));
        array[i] = itemName;
        Log.d("VALUE ",itemName+"name"); //There i geting all values
        i++;
    }
    return array[i]; //error showing this line

In my fragment i am calling this function to fetching itemname in string []

           String[] ItemNameArray = new String[list_counts];
                    for (int i = 0; i < list_counts; i++) {
                        ItemNameArray[i] = listcatDb.itemname();
                    }

Solution

  • you just return array. Because i value is increased inside the while loop. so just return array then use array values in the main thread or if you want to return string use i-1;

    return array;