Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android SQlite Leak Problem with CursorAdapter

Tags:

android

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

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

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?

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

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.

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.

like image 281
Yashima Avatar asked Mar 07 '11 21:03

Yashima


1 Answers

You should call sqliteHelper.open() in onCreate() and sqliteHelper.close() in onDestroy().

Activity Lifecycle explains the lifecycle in detail.

like image 85
Matthew Willis Avatar answered Oct 31 '22 00:10

Matthew Willis