android - 从sqlite数据库中获取总数

标签 android database sqlite

我有一个包含多个列的数据库(Android 上的 sqlite): _id, 日期, 小时, 注释

数据库是这样创建的:

    private static final String DATABASE_CREATE =
    "create table worked (_id integer primary key autoincrement, "
    + "datum text not null, hour text not null, " 
    + "note text);";

最后,我想从我的数据库中取出小时和分钟的总和,并将其返回到我的 mainActivity。

我试着这样做:

public int getTotalHours(){
    Cursor c = db.rawQuery("select hour from " + DATABASE_TABLE, null);
    int total = 0;
    Date hours = new Date();
    SimpleDateFormat hourFormat = new SimpleDateFormat("HH:mm");
    c.moveToFirst();
    for(int i = 0; i<c.getCount(); i++){
        String uur = c.getString(i);
        try {
            hours = hourFormat.parse(uur);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        total += hours.getHours();
    }
    return total;
}

但我的查询中已经出现错误。我也不知道如何以正确的方式提取数据,因为查询错误我无法测试...

我得到的错误:

Failed to read row 0, column 1 from a cursorWindow which has 5 rows, 1 columns.

我希望我的方法是正确的,并且有人可以帮助我。 提前致谢!

最佳答案

正确循环遍历记录,检索正确的列索引,然后关闭游标:

public int getTotalHours(){
    Cursor c = db.rawQuery("select hour from " + DATABASE_TABLE, null);
    if (c == null)
        return 0;

    try{
        int total = 0;
        Date hours = new Date();
        SimpleDateFormat hourFormat = new SimpleDateFormat("HH:mm");
        while(c.moveToNext())
        {
            String uur = c.getString(0);
            try {
                hours = hourFormat.parse(uur);
                total += hours.getHours();
            } catch (ParseException e) {
                e.printStackTrace();
            }           
        }

        return hours;
    }finally{
        c.close();
    }
}

关于android - 从sqlite数据库中获取总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14541095/

相关文章:

database - apex 如何从一个应用程序中的链接登录到另一个应用程序?

c# - 迭代 IQueryable 而不调用 ToList()

java - 无法将数据库数据填充到 jcombobox 中

ruby-on-rails - 构建新的 Rails 应用程序错误加载 'sqlite3' 没有明显的写入版本

c# - SQLite.Net,SQLite 位数据类型的 C# 等效项

android - 如何在 ButterKnife 中绑定(bind) XML fragment ?

java - 如何为带有交互式通知的网络广播流创建 Android 前台服务?

使用 FULLTEXT 索引的 MySQL 查询速度慢

android - View.onDraw() --- 它什么时候被调用?

android - 更新 TextView 时呈现缓慢