我有一个包含多个列的数据库(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/