SQLite exception: Database is locked issue SQLite exception: Database is locked issue sqlite sqlite

SQLite exception: Database is locked issue


After doing some effort I did it (My app was working on perfect till android 2.3 but got db lock error when I used to run it on HoneyComb tablet).
I did using Semaphores (using lock in critical sections).

Example 1

public class DbExp extends SQLiteOpenHelper{    public static String Lock = "dblock";    private static final String DATABASE_NAME = "db.db";    private static final String TABLE_NAME = "table_name";    public void delete(Context mContext){        synchronized(Lock) {            SQLiteDatabase db  = getWritableDatabase();            db.delete(TABLE_NAME, null, null);            db.close();        }    }    public void insert(){        synchronized(Lock) {            SQLiteDatabase db  = getWritableDatabase();            db.insert(TABLE_NAME, ..., ...);            db.close();        }    }}

Example 2

public class DB {    public static String Lock = "dblock";    private static final String DATABASE_NAME = "db.db";    private static final String TABLE_NAME = "table_name";    public void delete(Context mContext){        synchronized(Lock) {            SQLiteDatabase db  = mContext.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);            db.delete(TABLE_NAME, null, null);            db.close();        }    }    public void insert(Context mContext){        synchronized(Lock) {            SQLiteDatabase db  = mContext.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);            db.insert(TABLE_NAME, ..., ...);            db.close();        }    }}

Hope this would help Anyone in future :)


If your using Fragments and it happens with orientation changes, its because you have two instances of the same Fragment and they both have their own instance of a Db helper class of some kind. In order to make it work you either have to destroy your fragment on orientation change and rebuild it, or find a way to destroy the Db helper class. This is only for Fragments with orientation issues. I had to do alot of troubleshooting to figure it out, so hopefully someone finds this helpful


This was the Reason for me:

I forgot to end transaction in my function call after inserting into db .So when i tried to insert another record from another activity i got database locked exception. Adding the below statement solved my issue.

sqlDB.endTransaction();