java.lang.ArrayIndexOutOfBoundsException: length=0; index=0 - Database Reading - Android

Federico Belotti picture Federico Belotti · Mar 19, 2015 · Viewed 24k times · Source

I created a method that reads data from a database and puts it in a String array. Android Studio doesn't give syntax errors but when i launch my app the log says:

03-19 16:31:20.938    2518-2518/com.mms.dailypill E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.mms.dailypill, PID: 2518
java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
        at com.mms.dailypill.DBManager.getMedicines(DBManager.java:56)

The method code is:

public String[] getMedicines()
{
    SQLiteDatabase db = dbManager.getWritableDatabase();
    String[] columns = {dbManager.getName(), dbManager.getFormat(), dbManager.getAmount(), dbManager.getExp_date(), dbManager.getTime()};
    Cursor cursor = db.query(dbManager.getTableName(), columns, null, null, null, null, null);
    String[] medicines = {};

    String name, format, exp_date, time;

    int amount;
    int count = 0;
    while(cursor.moveToNext())
    {
        name = cursor.getString(0);
        format = cursor.getString(1);
        amount = cursor.getInt(2);
        exp_date = cursor.getString(3);
        time = cursor.getString(4);
        medicines[count] = "Name: " + name + " Format: " + format + " Amount: " + amount + " Expiration Date: " + exp_date + " Time: " + time;
        count++;
    }
    db.close();
    return medicines;
}

As the log says, the exception is given on the line 56:

time = cursor.getString(4);

The table i read has 6 columns: id, name, format, amount, exp_date, time. I only want to show the entire table without the id column, so when i call the getString() method i start from the index 1 and not from 0.

I really can't understand where the problem is, so if someone can help me i will appreciate it. Thanks in advance!

Answer

Mina Fawzy picture Mina Fawzy · Nov 30, 2015
java.lang.ArrayIndexOutOfBoundsException: length=0; index=0 

even you solve your problem , but I would like to explain why this error occurred , this error happen when you initialize empty array without size , or wrong initialize in this case String[] medicines = {}; its empty with size 0 , then he try add value at first index 0 that not exist , so the solution initialize with his list size String[] medicines = new String[cursor.getCount()];

Notice

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You have seen an example of arrays already, in the main method of the "Hello World!" application. This section discusses arrays in greater detail.

Summary

one array created it take fixed size , not like array list you can add as you want.

Source