计算数据库中所有行的方法使我的应用程序崩溃

Method to count all rows in my database crashes my app

我正在尝试计算我的应用程序中的所有行。一旦我调用以下方法,应用程序就会崩溃:

public int getDBPlacesCount() {
        String countQuery = "SELECT  * FROM " + TABLE_DB_VERLADESTELLEN_Eintrag;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        // return count
        return cursor.getCount();
    }

异常:

Caused by: java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteQuery: SELECT * FROM orte

谁能告诉我我做错了什么?

您试图获取游标计数,但上面的行关闭了与数据库的连接。您应该先获取计数,然后关闭连接,例如:

public int getDBPlacesCount() {
        String countQuery = "SELECT  * FROM " + TABLE_DB_VERLADESTELLEN_Eintrag;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        int count = cursor.getCount();
        cursor.close();

        // return count
        return count
    }

Can someone tell me what I did wrong?

您试图从已经是 closed 的光标 read,这是错误的。

您需要如下所示更改代码:

public int getDBPlacesCount() {
    try {
        String countQuery = "SELECT  * FROM " + TABLE_DB_VERLADESTELLEN_Eintrag;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        long count = cursor.getCount();

        // return count
        return count;
     } catch(SQLException exe) {
        //log exceptions
     } finally {
       if(cursor != null) {
          //always close the cursor in finally and make it null
          cursor.close();
          cursor = null;
       }
     }
}

此外,请确保关闭 finally 块中的游标以避免泄漏。