Android的SQLite的泄漏问题与的CursorAdapter问题、Android、SQLite、CursorAdapter

2023-09-08 09:46:24 作者:作业的葬礼我必盛装出席

我有一个的ListView 从SQLite数据库显示的数据。我延长的CursorAdapter 来做到这一点。下面code在我的 ListActivity 有一个很大的问题:它的手离开光标移到的CursorAdapter

I have a ListView that displays data from an sqlite database. I extended CursorAdapter to do this. The following code in my ListActivity has one big problem: it hands off the cursor to the CursorAdapter

private boolean refreshListView() {
    final boolean result;
    SqliteHelper sqliteHelper = new SqliteHelper(this);
    sqliteHelper.open();
    final Cursor cursor = sqliteHelper.fetchAll();
    if (cursor.getCount() == 0) {
       //handling some stuff
    } else {
        startManagingCursor(cursor);
        final MyCursorAdapter measures = new MyCursorAdapter(this, cursor);
        setListAdapter(measures);
        result = true;
    }        
    return result;
}

我注意到,这code会导致频繁的 IllegalStateExceptions SQLiteDatabase创建永不关闭。

I noticed that this code leads to frequent IllegalStateExceptions "SQLiteDatabase created and never closed".

我试图通过关闭数据库连接来解决这个问题。但如果我关闭它从这个方法,我得到 SQLiteMisuseException 对此我猜测是由适配器仍在工作,并且仍然需要光标原因引起的?

I tried to fix this by closing the database connection. But if I close it from this method I get SQLiteMisuseException which I am guessing is caused by the Adapter still being at work and the cursor is still needed?

我也尝试从的onPause关闭数据库()。然而,这并不修复泄漏。

I also tried closing the database from onPause(). This does not fix the leakage however.

我不希望产生任何种类的内存或其他泄漏的应用程序。但我不知道我做错了。我还没有发现任何回调或生命周期的方法或者 ListActivity 的CursorAdapter 这给了我一个提示,我应该怎么处理这个。

I don't want an app that produces any kind of memory or other leak. But I have no idea what I am doing wrong. I have not found any call back or lifecycle methods in either ListActivity or CursorAdapter that gave me a hint how I should be handling this.

我会就如何解决这一问题的任何暗示感激。我开始怀疑整个结构是错误的。如果需要,我可以发布更多code。

I'd be grateful for any hint on how to fix this. I am starting to suspect that the entire construct is just wrong. I can post more code if needed.

推荐答案

您应该叫 sqliteHelper.open()的onCreate() sqliteHelper.close()的onDestroy()

活动生命周期详细解释了生命周期。

Activity Lifecycle explains the lifecycle in detail.