Problem with SQlite for Android using CursorAdapter

I have a ListView that displays data from sqlite database. I have expanded the CursorAdapter to do this. The following code in my ListActivity has one big problem: it moves the cursor to 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 is created and never closes."

I tried to fix this by closing the database connection. But if I close it from this method, do I get a SQLiteMisuseException , which I assume is caused by the adapter still working and the cursor still needed?

I also tried closing the database from onPause() . However, this does not eliminate the leak.

I do not want the application to cause any memory or other leak. But I have no idea what I'm doing wrong. I did not find any callback or lifecycle ListActivity in ListActivity or CursorAdapter that gave me a hint how I should handle this.

I would be grateful for any hint on how to fix this. I am beginning to suspect that the whole construction is erroneous. If necessary, I can send more code.

+7
source share
1 answer

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

The life cycle of an activity describes the life cycle in detail.

+9
source

All Articles