Java 方法计算数据库中的所有行使我的应用程序崩溃
我正在尝试计算应用程序中的所有行。我一调用以下方法,应用程序就会崩溃:Java 方法计算数据库中的所有行使我的应用程序崩溃,java,android,exception,android-sqlite,illegalstateexception,Java,Android,Exception,Android Sqlite,Illegalstateexception,我正在尝试计算应用程序中的所有行。我一调用以下方法,应用程序就会崩溃: public int getDBPlacesCount() { String countQuery = "SELECT * FROM " + TABLE_DB_VERLADESTELLEN_Eintrag; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(countQuer
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选择*
有人能告诉我我做错了什么吗?您试图获取光标计数,但上面的一行关闭了与数据库的连接。您应该先获取计数,然后关闭连接,例如:
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
}
有人能告诉我我做错了什么吗
您试图从已关闭的光标读取,这是错误的
您需要更改代码,如下所示:
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
块中的光标,以避免泄漏。@Glave My Glave!祝你好运