2
\$\begingroup\$

I find this code quite ugly, but in fact, I can't find a finer way of achieving the goal.

private static final String TABLE_NAME = "table_name";
private static final String[] allNeededColumns = {"col_id","col_one","col_two"};

public int[] getItemIds(int category_id) {
    ArrayList<Integer> ids = new ArrayList<Integer>();
    Cursor c = getDatabase().query(TABLE_NAME, allNeededColumns, CATEGORY_ID + "=" + category_id, null, null, null, null);
    c.moveToFirst();
    while(!c.isAfterLast()){
        ids.add(Integer.valueOf(c.getInt(2)));
        c.moveToNext();
    }
    return convertIntegers(ids);
}

public static int[] convertIntegers(ArrayList<Integer> integers)
{
    int[] ret = new int[integers.size()];
    Iterator<Integer> iterator = integers.iterator();
    for (int i = 0; i < ret.length; i++)
    {
        ret[i] = iterator.next().intValue();
    }
    return ret;
}

The purpose is to get out of table int array, where IDs are item IDs from category bycategory_id`.

The problem is, I need some kind of expandable collection to add DB result ID to, and return primitives array, and I find it prettier than creating new int[] variable for each iteration on Cursor.

Can you think of a prettier solution?

\$\endgroup\$
3
  • \$\begingroup\$ blame java for the way primitives are handled. you can use a library such as Guava to get around that. \$\endgroup\$
    – Adam
    Commented Aug 12, 2012 at 10:07
  • \$\begingroup\$ Have you considered using Cursor.getCount() to find out how many ids is here? Then you can allocate an array of the needed size in advance and avoid using an expandable collection. \$\endgroup\$ Commented Aug 13, 2012 at 15:50
  • \$\begingroup\$ @DarthBeleg good point good sir :) Thank you \$\endgroup\$ Commented Aug 13, 2012 at 16:32

1 Answer 1

2
\$\begingroup\$

If you were going to use the above you could still utilise Java's autoboxing feature, but there is a shorter form as hinted at by Darth Beleg.

Untested:

int[] ret = new int[c.getCount()];
if (c.moveToFirst())
    for (int i = 0; i < c.getCount();) {
        ids[i++] = c.getInt(2);
        c.moveToNext();
    }
}

Although it is not pertinent to your case it is worth remembering that

ret[i] = iterator.next().intValue();

could throw a NPE.

\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.