我在参加此 Activity 后收到此错误,开始新 Activity ,然后回来。当我第一次加载 Activity 时不会发生这种情况。在功能上一切正常......但我仍然收到此错误。
ERROR/Cursor(1059): Finalizing a Cursor that has not been deactivated or closed. database = /data/data/com.roger.testapp/databases/data, table = null, query = SELECT MAX(_id) FROM record
03-02 16:47:21.835: ERROR/Cursor(1059): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
在onCreate中:
mDbHelper = new CommonDbAdapter(this);
mDbHelper.open();
fillData();
fillData() 在我的 dbhelper 中调用 fetchNote,游标用于一些事情,如果 rowId == 0,这意味着我没有选择一个项目进入这个 Activity ,我想获得最后一行那张 table 如果 rowId = 其他,那么我捕获那一行。我认为问题出在这里的某个地方,我只是不确定。
public Cursor fetchNote(long rowId, String table, String columns) throws SQLException {
if (rowId == 0) {
String query = "SELECT MAX(_id) FROM record";
Cursor cursor = mDb.rawQuery(query, null);
rowId = 0;
if (cursor.moveToFirst())
{
rowId = cursor.getInt(0);
}
}
Cursor mCursor =
mDb.query(true, table, new String[] {KEY_ROWID,
columns}, KEY_ROWID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
在onDestroy中:
super.onDestroy();
if (mDbHelper != null) {
mDbHelper.close();
}
还有,我是startManagingCursor
最佳答案
不要在 onDestroy
中关闭数据库。使用完后立即关闭它(确保在关闭数据库之前关闭每个游标)。 onDestroy 可能不会在您期望的时候被调用。
此外,在使用完 Cursor
对象后关闭它。
编辑:
由于您的 Activity 正在管理您的 Cursor
,您可以考虑停止管理它并在 onPause
方法中关闭所有内容,并在 onResume
中打开所有内容并fillData
再次。如果您可以更改您的代码,这样您就不会依赖管理游标的 Activity ,那么您就不需要保留打开的数据库对象并担心它们。
关于java - 不关闭游标或数据库对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5174069/