10
I use this class to manage connection to underlying SQLiteDatabase
public class BasicDataSource {
protected DatabaseHandler dbHelper;
protected volatile SQLiteDatabase readable_database;
protected volatile SQLiteDatabase writable_database;
protected Object read_lock = new Object();
protected Object write_lock = new Object();
protected Context context;
protected BasicDataSource(Context ctx) {
dbHelper = DatabaseHandler.getInstance(ctx);
getReadableDatabase();
dbHelper.onCreate(getWritableDatabase());
this.context = ctx;
}
public synchronized void close() {
dbHelper.close();
}
protected void closeInsertHelpers(InsertHelper... helpers) {
for (InsertHelper ih : helpers) {
if (ih != null)
ih.close();
}
}
protected SQLiteDatabase getReadableDatabase() {
synchronized (read_lock) {
if (readable_database == null || !readable_database.isOpen()) {
readable_database = dbHelper.getReadableDatabase();
}
return readable_database;
}
}
protected SQLiteDatabase getWritableDatabase() {
synchronized (write_lock) {
if (writable_database == null || !writable_database.isOpen()) {
writable_database = dbHelper.getWritableDatabase();
}
return writable_database;
}
}
protected synchronized void open() throws SQLException {
getReadableDatabase();
getWritableDatabase();
}
}
It contains two locks, one for read, second for write. But I'm still occasionally getting this kind of exception:
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurre