Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I find this code quite ugly, but in fact, I don't see any finest way to achieve 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 by category_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 each iteration on Cursor.

Can't you think about some prettier solution?

share|improve this question
blame java for the way primitives are handled. you can use a library such as Guava to get around that. – codesparkle Aug 12 '12 at 10:07
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. – Darth Beleg Aug 13 '12 at 15:50
@DarthBeleg good point good sir :) Thank you – Marek Sebera Aug 13 '12 at 16:32

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.