Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从表中选择计数(*)时Android SQLite游标超出边界异常_Java_Android_Sqlite - Fatal编程技术网

Java 从表中选择计数(*)时Android SQLite游标超出边界异常

Java 从表中选择计数(*)时Android SQLite游标超出边界异常,java,android,sqlite,Java,Android,Sqlite,下面的函数给了我一个越界异常 public void count(){ SQLiteDatabase db = table.getWritableDatabase(); String count = "SELECT count(*) FROM table"; Cursor mcursor = db.rawQuery(count, null); int icount = mcursor.getInt(0); System.out.println("NUMBE

下面的函数给了我一个越界异常

public void count(){
    SQLiteDatabase db = table.getWritableDatabase();
    String count = "SELECT count(*) FROM table";
    Cursor mcursor = db.rawQuery(count, null);
    int icount = mcursor.getInt(0);
    System.out.println("NUMBER IN DB: " + icount);
}
这意味着返回数据库中的行数。有人知道怎么了吗?我是不是做错了这项工作?

你错过了

mcursor.moveToFirst();

public void count(){
    SQLiteDatabase db = table.getWritableDatabase();
    String count = "SELECT count(*) FROM table";
    Cursor mcursor = db.rawQuery(count, null);
    mcursor.moveToFirst();
    int icount = mcursor.getInt(0);
    System.out.println("NUMBER IN DB: " + icount);
}
但是您应该使用更好的方法来完成这项任务,比如DatabaseUtils的内置助手

比如

public long count() {
    return DatabaseUtils.queryNumEntries(db,'tablename');
}

当使用where查询总计数时,使用
DatabaseUtils.longForQuery()
获取第一列长值可能会有所帮助。它更简单,您不需要对光标进行大量操作。

需要将光标移动到第一行(也是唯一一行)


如果要获取特定ID或值的行数,可以使用此选项

public int numbersOfrows (int id) {
        SQLiteDatabase db = this.getReadableDatabase();
        int numbersOfrows = 0 ;

        Cursor c = db.rawQuery("select count(*) from table_name where Column_name = 'yourValue'")
        if (c.moveToFirst()){
            numbersOfrows = c.getInt(0);
        }

        return numbersOfrows ;
    }

艾丹,如果你觉得这是正确的答案,你应该点击“勾选”标记。有趣的是——我本以为创建一个新的光标会将其移动到第一条记录,而不是“在第一条之前”——很高兴安卓也加入了这个概念(我更习惯于只使用“在最后一条之后”)。还想知道,这样做(我希望如此)或
SELECT*FROM table
,然后在结果光标上
getCount()
,有什么更好的方法?@J-16 SDiZ您只能在15分钟后将答案标记为已接受@Joubarc可能DatabaseUtils比使用getCount()进行的代码优化得多
DatabaseUtils
可能会得到很好的优化,但是如果您已经完成了查询,并且拥有了
光标
,那么我非常怀疑在其上调用
getCount()
是否会更慢。@Pentium10:“DatabaseUtils.queryNumEntries”仍然是一个不错的选择,还是已经被弃用了?
public int numbersOfrows (int id) {
        SQLiteDatabase db = this.getReadableDatabase();
        int numbersOfrows = 0 ;

        Cursor c = db.rawQuery("select count(*) from table_name where Column_name = 'yourValue'")
        if (c.moveToFirst()){
            numbersOfrows = c.getInt(0);
        }

        return numbersOfrows ;
    }