0

我正在尝试根据月份对表格列求和,但出现以下异常:

   java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.

功能

public static float test(SQLiteDatabase db) {

    String expenditure = MyDatabaseContract.TableExpenditure.ATTR_EXPENDITURE;
    String table = MyDatabaseContract.TableExpenditure.TABLE_EXPENDITURE;
    String date = MyDatabaseContract.TableExpenditure.ATTR_DATE;

    String query = "SELECT SUM(" + expenditure + ") FROM " + table + " WHERE strftime('%m', date)=11";
    Cursor cursor = db.rawQuery(query, null);


    float total = 0;
    if (cursor.moveToFirst())
        total = cursor.getInt(cursor.getColumnIndex("Total"));// get final total

    return total;
}

桌子

public static class TableExpenditure {

    public static final String TABLE_EXPENDITURE = "expenditure_table";

    public static final String ATTR_PRIMARY_KEY = "pk_expendituretable";
    public static final String ATTR_DATE = "date";
    public static final String ATTR_CATEGORY = "category";
    public static final String ATTR_EXPENDITURE = "expenditure";
    public static final String ATTR_COMMENT = "comment";

    public static final int N_COLUMNS = 5;

    public static final String SQL_CREATE_TABLE =
            "CREATE TABLE " + TABLE_EXPENDITURE + "(" + ATTR_PRIMARY_KEY + " INTEGER PRIMARY KEY AUTOINCREMENT," +  ATTR_DATE + " DATE," + ATTR_CATEGORY + " TEXT," +
                    ATTR_EXPENDITURE + " REAL," + ATTR_COMMENT + " TEXT"  + ")";
}

在调试器中,光标包含一项,但在调用 getInt(..) 时应用程序崩溃

4

1 回答 1

1

为此结果创建的列:

SUM(" + expenditure + ")

不叫Total
将 sql 语句更改为:

String query = "SELECT SUM(" + expenditure + ") AS Total FROM " + table + " WHERE strftime('%m', date)=11";

这样,您就可以为Total列指定名称(别名)。
或者由于只返回 1 列,请执行以下操作:

total = cursor.getInt(0);
于 2018-12-19T14:03:51.947 回答