SQLITE EXCEPTION : Unable to close due to unfinalised statements | Techbirds

When we work with sqlite ,we do the common mistake.

We create the nested cursors and usually we forgot to close all the cursors.So this will throw exception.And  in case of devices with lower versions of sqlite or your application will crash when you will try to close the database.Appliaction may not crash in phones with higher versions.But make sure you are clearing all the cursors.
Example code snippet given below:

Suppose we are quering any data which is returing a cursor.

And we are creating nesting cursors within that cursor like this:

Cursor cur1 = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null, ContactsContract.Contacts.DISPLAY_NAME + ” COLLATE LOCALIZED ASC”);

while (cur1.moveToNext()) {

String columns[] = {ContactsContract.CommonDataKinds.Event.TYPE};

String where = Event.TYPE + “=” + Event.TYPE_BIRTHDAY + ” and ” + Event.MIMETYPE + ” = ‘” + Event.CONTENT_ITEM_TYPE + “‘ and ” + ContactsContract.Data.CONTACT_ID + ” = ”

+ contactId;

String[] selectionArgs = null;

Cursor birthdayCur = cr.query( ContactsContract.Data.CONTENT_URI, columns,

where, selectionArgs, null);

if (birthdayCur.getCount() > 0) { while (birthdayCur.moveToNext()) { String birthday = birthdayCur .getString(birthdayCur

.getColumnIndex                                                                                                                       (ContactsContract.CommonDataKinds.Event.START_DATE));





So, In this example we are creating cursors in loop but we are not closing all the cursors.So,when you will call db.close() statement you will get this exception.

Caused by: android.database.sqlite.SQLiteException: unable to close due to unfinalised statements at android.database.sqlite.SQLiteDatabase.dbclose(Native Method) at android.database.sqlite.SQLiteDatabase.onAllReferencesReleased(SQLiteDatabase.java:322) at android.database.sqlite.SQLiteDatabase.close(SQLiteDatabase.java:990) at android.database.sqlite.SQLiteOpenHelper.close(SQLiteOpenHelper.java:191) at com.companionfree.WLThemeViewer.DbAdapter.close(DbAdapter.java:163) at com.companionfree.WLThemeViewer.Viewer.getNavData(Viewer.java:179) at com.companionfree.WLThemeViewer.Viewer.onCreate(Viewer.java:65) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2633)

… 11 more

So,when you creating cursors in a loop.Make sure you are clearing all the cursors.You are closing cursors in loop.

2,228 total views, 1 views today

Share this Onfacebook-2102404twitter-5992530linkedin-2713922google-2551080