So, I came up with some idea, and I wonder if this is possible.
Let's say I have several tables (database models), each of which is represented by a certain class. I do not want to use a singleton open-helper template, so I created a simple class to provide a single database instance. My idea is that as long as all tables contain a reference to SQLiteDatabase (returned by the open helper), they will all work with the same DB instance and probably will not be needed to synchronize work with the database, since the open helper is . When the last table finishes, GC will assemble an open helper (since the last link will be a weak link) -> finalize () is called, and I close db during this method to prevent any warning from the OS. My question is: can this work? Will it automatically close the database and will it leak or throw an exception?
Here is my class:
public class DatabaseHelper { private static WeakReference<SomeCustomOpenHelper> sDBOpenHelper; private void notifyDBCreate(SQLiteDatabase db) { for (DBTable table : mTables) { table.onDBCreate(db); } } private void notifyDBUpgrade(SQLiteDatabase db) { for (DBTable table : mTables) { table.onDBUpgrade(db); } } public SQLiteDatabase getDatabase(boolean readOnly) { SomeCustomOpenHelper dbHelper = sDBOpenHelper.get(); if (dbHelper == null) { dbHelper = new SomeCustomOpenHelper(context, name, factory, version, new DatabaseEventsCallback()); sDBOpenHelper = new WeakReference<SomeCustomOpenHelper>(dbHelper); } if (readOnly) { return dbHelper.getReadableDatabase(); } else { return dbHelper.getWritableDatabase(); } } private class DatabaseEventsCallback implements IDatabaseEventsCallback { @Override public void onCreate(SQLiteDatabase db) { notifyDBCreate(db); } @Override public void onUpgrade(SQLiteDatabase db) { notifyDBUpgrade(db); } } interface IDatabaseEventsCallback { void onCreate(SQLiteDatabase db); void onUpgrade(SQLiteDatabase db); } private static class SomeCustomOpenHelper extends SQLiteOpenHelper { private IDatabaseEventsCallback mCB; public SomeCustomOpenHelper(Context context, String name, CursorFactory factory, int version, IDatabaseEventsCallback cb) { super(context, name, factory, version); mCB = cb; } @Override public void onCreate(SQLiteDatabase db) { mCB.onCreate(db); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { mCB.onUpgrade(db); } @Override protected void finalize() throws Throwable { this.close(); super.finalize(); } } }
android synchronization weak-references sqliteopenhelper
Teodor
source share