1

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();
        }
    }
}
2
  • You could use the toArray method of your list. mArray = list.toArray(new long[list.size()]). Commented Jun 6, 2014 at 12:39
  • I take it back, just realised this doesn't work for arrays of primitive types... Commented Jun 6, 2014 at 12:43

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.