4

Pretty sure this is an easy one, but i'm getting confused by all the examples that adapt the data returned from a cursor into different views. I just want to run a rawquery and put each item of data returned into a float array (so that i can add them up later). What do i need to use for this? Thanks

2
  • 1
    Have you forgotten to initialize the budgetInArray (presumably you want to do that just after the "numRows = incomeCursor.getCount()" line)? Commented Jan 30, 2011 at 15:28
  • Yes that was exactly the problem, just got there myself -_- Thanks for pointing it out too :) Commented Jan 30, 2011 at 15:32

2 Answers 2

9

You'll still have a cursor when you query your database, but once you got the cursor you could iterate over it, pulling out the values you need into an array, like this:

DbAdapter db = new DbAdapter(mContext);
    int columnIndex = 3; // Whichever column your float is in.
    db.open();
    Cursor cursor = db.getAllMyFloats();
    float[] myFloats = new float[cursor.getCount()-1];

    if (cursor.moveToFirst())
    {                       
        for (int i = 0; i < cursor.getCount(); i++)
        {
            myFloats[i] = cursor.getFloat(columnIndex);
            cursor.moveToNext();
        }           
    }
    cursor.close();
    db.close();

    // Do what you want with myFloats[].
Sign up to request clarification or add additional context in comments.

3 Comments

ahhh wicked thank you very much! The only thing i don't understand is the need to use columnIndex? I suppose i'll find out if i look into the method. I assume the actual rawQuery is done in getAllMyFloats right? Cheers this really helped.
oh also one other thing, do the columns start at an index of 0 or 1?
If you have a table with several columns, then you'll need the column index to get the specific data field you're looking for. Columns are zero-indexed.
3

Don't minus by 1 in float[] myFloats = new float[cursor.getCount()-1]; because (int i =0) or i start from 0. If you use it, will appear Java.lang.IndexOutOfBoundsException. You need array index until [cursor.getCount()], not until [cursor.getCount()-1]. So the correct thing is float[] myFloats = new float[cursor.getCount()];

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.