Putting cursor data into an array

Rakeeb Rajbhandari picture Rakeeb Rajbhandari · Sep 18, 2013 · Viewed 26.5k times · Source

Being new in Android, I am having trouble dealing with the following:

public String[] getContacts(){
    Cursor cursor = getReadableDatabase().rawQuery("SELECT name FROM contacts", null);
    String [] names = {""};
    for(int i = 0; i < cursor.getCount(); i ++){
            names[i] = cursor.getString(i);
    }
    cursor.close();
    return names;
}

The following gives me the following error:

09-18 10:07:38.616: E/AndroidRuntime(28165): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sqllitetrial/com.example.sqllitetrial.InsideDB}: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 5

I am trying to extract the data inside the cursor to an array. Can someone help me with the implementation.

Answer

Su-Au Hwang picture Su-Au Hwang · Sep 18, 2013
names.add(cursor.getString(i));

"i" is not the cursor row index, it's the column index. A cursor is already positioned to a specific row. If you need to reposition your cursor. Use cursor.move or moveToXXXX (see documentation).

For getString/Int/Long etc. you just need to tell the cursor which column you want. If you don't know the columnIndex you can use cursor.getColumnIndex("yourColumnName").

Your loop should look like this:

public String[] getContacts(){
    Cursor cursor = getReadableDatabase().rawQuery("SELECT name FROM contacts", null);
    cursor.moveToFirst();
    ArrayList<String> names = new ArrayList<String>();
    while(!cursor.isAfterLast()) {
        names.add(cursor.getString(cursor.getColumnIndex("name")));
        cursor.moveToNext();
    }
    cursor.close();
    return names.toArray(new String[names.size()]);
}