-1

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?

Glave
  • 137
  • 1
  • 1
  • 10

2 Answers2

2

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
    }
BlackHatSamurai
  • 23,275
  • 22
  • 95
  • 156
1

Can someone tell me what I did wrong?

You have tried to read from the cursor which is already closed, which is wrong.

You need to change your code as shown below:

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

Also, ensure that you are CLOSING the cursor in the finally block to avoid the leakage.

Vasu
  • 21,832
  • 11
  • 51
  • 67