Android java.lang.IllegalStateException:尝试重新打开已关闭的对象(尝试关闭)

Android java.lang.IllegalStateException:尝试重新打开已关闭的对象(尝试关闭),android,sqlite,android-sqlite,Android,Sqlite,Android Sqlite,我正在尝试获取数据库中记录的总数,但数据库每次都会崩溃,原因是java.lang.IllegalStateException:尝试重新打开已关闭的对象:android.database.sqlite.SQLiteQuery(mSql=SELECT*FROM login)。请帮我纠正这个错误 public int getRecordsCount() { String countQuery = "SELECT * FROM " + TABLE_LOGIN; SQL

我正在尝试获取数据库中记录的总数,但数据库每次都会崩溃,原因是
java.lang.IllegalStateException:尝试重新打开已关闭的对象:android.database.sqlite.SQLiteQuery(mSql=SELECT*FROM login)
。请帮我纠正这个错误

public int getRecordsCount() {
        String countQuery = "SELECT  * FROM " + TABLE_LOGIN;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        if(cursor != null && !cursor.isClosed()){
            cursor.close();
        }   
        // return count

        return cursor.getCount();
    }

在关闭光标之前,应该调用
getCount()

移动:

下:

if(cursor != null && !cursor.isClosed()){
    cursor.close();
} 
像这样:

 cursor.getCount();
java.lang.IllegalStateException:尝试重新打开已关闭的

您的错误被抛出,因为您在已关闭的
cursor
上调用了
cursor.getCount()
,这是不允许的

因此,或者尝试使用try finally块,在finally block中关闭
光标
,或者将
Cursor.getCount()
分配给int value并立即关闭
光标

但我建议您使用第一种方法:

public int getRecordsCount() {
    int count = 0;
    String countQuery = "SELECT  * FROM " + TABLE_LOGIN;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);



    if(cursor != null && !cursor.isClosed()){
        count = cursor.getCount();
        cursor.close();
    }   
    return count;
}

我知道这很旧,但我的问题是,在
onCreate()
中,我在执行
db.execSQL(TABLE\u CREATE)
后调用了
db.close()

onCreate
dbHelper.getReadableDatabase()之后自动调用


这导致它崩溃,因为随后它使用一个已关闭的对象从数据库中检索所有值。一旦我从
onCreate
中删除了
db.close()
,一切都正常了

删除
游标.close()
语句

对于我来说,问题是我正在为更新查询关闭finally块中的db实例

对于无法使用上述解决方案修复的用户,请尝试检查更新查询

public int getRecordsCount() {
    int count = 0;
    String countQuery = "SELECT  * FROM " + TABLE_LOGIN;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);



    if(cursor != null && !cursor.isClosed()){
        count = cursor.getCount();
        cursor.close();
    }   
    return count;
}
public int getRecordsCount() {
   String countQuery = "SELECT * FROM " + TABLE_LOGIN;
   SQLiteDatabase db = this.getReadableDatabase();
   Cursor cursor = db.rawQuery(countQuery, null);
   int count = 0;
   try {
      if (cursor.moveToFirst())) {
         count = cursor.getCount();
      }
      return count;
   }
   finally {
      if (cursor != null) {
         cursor.close();
      }
   }
}