Take the 2-minute tour ×
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 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?

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

1 Answer 1

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.

share|improve this answer

Your Answer

 
discard

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

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