代码之家  ›  专栏  ›  技术社区  ›  Glave

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

  •  -1
  • Glave  · 技术社区  · 8 年前

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

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

    例外:

    原因:java.lang.IllegalStateException:尝试重新打开 已关闭对象:SQLiteQuery:从orte中选择*

    有人能告诉我我做错了什么吗?

    2 回复  |  直到 8 年前
        1
  •  2
  •   BlackHatSamurai    8 年前

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

    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
        }
    
        2
  •  1
  •   Vasu    8 年前

    read 从已经存在的光标 closed ,这是错误的。

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

    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 堵塞以避免泄漏。