如何将字符串数据存储到sqlite for android的整数数组中

时间:2015-05-15 12:19:31

标签: java android arrays

我想将sqlite数据转换为整数数组。

public Integer[] getch() {

        SQLiteDatabase database = this.getReadableDatabase();
        Cursor cursor = database.rawQuery("SELECT sum(sales) FROM sales group by outlet_code order by ordered_date", null);
        // String[] array = new String[crs.getCount()];
        int columnIndex = 3;
        Integer[] in = new Integer[cursor.getCount()];

        if (cursor.moveToFirst())
        {
            for (int i = 0; i < cursor.getCount(); i++)
            {
                in[i] = cursor.getInt(columnIndex);
                cursor.moveToNext();
            }
        }
        cursor.close();
        return in;
    }

我需要以下格式的结果:

int[] income = { 2000,2500,2700,3000,2800,3500,3700,3800, 0,0,0,0};

Integer[] income =  controller.getch();

我收到了错误:

  

无法从CursorWindow读取第0行第3列。确保光标是   在从中访问数据之前正确初始化

1 个答案:

答案 0 :(得分:0)

为什么使用columnIndex = 3,您的SQL查询只返回1列,Sum(sales),因此您应将columnIndex值设置为0

试试这个

public Integer[] getch() {

    SQLiteDatabase database = this.getReadableDatabase();
    Cursor cursor = database.rawQuery("SELECT sum(sales) FROM sales group by outlet_code order by ordered_date", null);
    // String[] array = new String[crs.getCount()];
    int columnIndex = 0;
    Integer[] in = new Integer[cursor.getCount()];

    if (cursor.moveToFirst())
    {
        for (int i = 0; i < cursor.getCount(); i++)
        {
            in[i] = cursor.getInt(columnIndex);
            cursor.moveToNext();
        }
    }
    cursor.close();
    return in;
}

希望这有帮助