How do i get data from an SQLITE database to an ar

2019-05-10 23:34发布

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条回答
一纸荒年 Trace。
2楼-- · 2019-05-11 00:26

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[].
查看更多
Emotional °昔
3楼-- · 2019-05-11 00:35

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()];

查看更多
登录 后发表回答