Luizje Luizje - 10 days ago 4
Android Question

Convert Android Cursor to ArrayList of arrays

I try to convert my Cursor data to a arraylist. But at the end all the data in the arraylist is overwrited with the last row. What do i do wrong?

Cursor c = myDbHelper.getLvl1Cata();
String[] data = new String[3];
c.moveToFirst();
while(!c.isAfterLast()) {
data[0] = Integer.toString(c.getInt(0));
data[1] = c.getString(1);
data[2] = Integer.toString(c.getInt(2));
Log.e("cc", data[1]);
catalogueData.add(data);
c.moveToNext();
}

Answer

Try this

Cursor c = myDbHelper.getLvl1Cata();
String[] data;
if (c != null) {
    while(c.moveToNext()) {
        data = new String[3]; // Note this addition
        data[0] = Integer.toString(c.getInt(0));
        data[1] = c.getString(1);
        data[2] = Integer.toString(c.getInt(2));
        Log.e("cc", data[1]);
        catalogueData.add(data);
    }
    c.close();
}

data is an array of strings. In the original code, you added the same array to your catalogueData structure several times. You changed the value of the array's contents each time, but it was still the same array object. So you ended up with catalogueData holding several references to a single array, and that array can only have one value for data[0]: the last thing you set it to.

This answer fixes that by using a new and different array for each row in the cursor.

Comments