Fletcher Johns
Fletcher Johns

Reputation: 1274

Create an array from Cursor

Of the following two methods (both of which overwrite long[] mArray), which would be preferred?

The first method iterates over the Cursor, calling ArrayList.add() for each row, then iterates over the ArrayList to copy the values to the array.

The second method iterates over the Cursor twice. Once, calling size++ each time to count the rows, and again to copy the values to the array.

public void arrayFromCursor1(Cursor cursor) {

    // create a temp ArrayList to add to as we don't
    // know how many rows are in the cursor
    List<Long> list = new ArrayList<Long>();
    // iterate over the cursor
    if (cursor.moveToFirst()) {
        do {
            list.add(cursor.getLong(cursor.getColumnIndex("column_name")));
        } while (cursor.moveToNext());
        // create a long[] of appropriate length and copy values from the
        // ArrayList using a for loop
        final int size = list.size();
        mArray = new long[size];
        for (int i = 0; i < size; i++) {
            mArray[i] = list.get(i);
        }
    }
}

public void arrayFromCursor2(Cursor cursor) {

    // no need for a temp ArrayList this time
    // iterate over the cursor simply counting the rows
    if (cursor.moveToFirst()) {
        int size = 0;
        do {
            size++;
        } while (cursor.moveToNext());
        // create a long[] of appropriate length and iterate over the
        // cursor again, this time with a for loop copying values to the array
        mArray = new long[size];
        cursor.moveToFirst();
        for (int i = 0; i < size; i++) {
            mArray[i] = cursor.getLong(cursor.getColumnIndex("column_name"));
            cursor.moveToNext();
        }
    }
}

Upvotes: 1

Views: 1410

Answers (1)

Fletcher Johns
Fletcher Johns

Reputation: 1274

I've come up with what I think is a clean, simple solution for creating an array from a Cursor. This is useful when storing arrays in foreign-key tables, and will work with primitives.

public long[] arrayFromCursor(Cursor cursor) {

    int length = cursor.getCount();
    long[] array = new long[length];

    if (cursor.moveToFirst()) {
        for (int i = 0; i < length; i++) {
            array[i] = cursor.getLong(cursor.getColumnIndex("column_name"));
            cursor.moveToNext();
        }
    }
    return array;
}

Upvotes: 1

Related Questions