Search code examples
javaandroidexceptionandroid-sqliteillegalstateexception

Method to count all rows in my database crashes my app


I am trying to count all rows in my app. As soon as I call the following method the app crashes:

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();
    }

The exception:

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

Can someone tell me what I did wrong?


Solution

  • You tried to get the cursor count, but the line above you close the connection to the database. You should get the count first, then close the connection, something like:

    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
        }