Luciano
Luciano

Reputation: 2798

Convert Android Cursor to ArrayList of arrays

I try to convert my Cursor data to a arraylist<String[]>. 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();
}   

Upvotes: 3

Views: 17436

Answers (3)

WarrenFaith
WarrenFaith

Reputation: 57672

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.

Upvotes: 12

Disha
Disha

Reputation: 21

Try this:

if(mycursor!=null){    
            do{
    TextView name = (TextView)view.findViewById(R.id.contact_name);               
    name.setText(cursor.getString(cursor.getColumnIndex
                (Displayname)));
    mycursor.moveToNext();
            }while (mycursor.isLast());
        }

Upvotes: 1

DeeV
DeeV

Reputation: 36035

Put String[] data = new String[3]; into the while loop. You're overwriting the array object with each iteration.

Upvotes: 0

Related Questions