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.
You should call sqliteHelper.open() in onCreate() and sqliteHelper.close() in onDestroy().
Activity Lifecycle explains the lifecycle in detail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With