I am using a DBManager layer, it holds as private member all all the SQLiteOpenHelpers for the tables. The class is as followed
public class DBManager
{
private static final String mTAG = "DBManager";
Context mContext = null;
DB1 mDB1 = null;
DB2 mDB2 = null;
public DBManager( Context context )
{
mContext = context;
mDB1 = new DB1( mContext );
mDB2 = new DB2( mContext );
}
@Override
protected void finalize() throws Throwable
{
Close();
super.finalize();
}
public void Close()
{
if( mDB1 != null ) mDB1.close();
if( mDB2 != null ) mDB2.close();
}
.... Public API towards the DB1/DB2....
}
The question is like this:
Currently I am using it in each activity I need the DB as a private member.
Maybe better to use it as singleton? Can I? If do – which context to pass?
Or any other way to use?
Thanks
Here’s what I do. Keep one instance of SqliteOpenHelper per-database. Do not keep more than one Helper for a single database. This can cause issues with writes if more than one thread are trying to write at the same time.
Keep the Helper instance as a singleton across your application process. Multiple Activity and Service clients can access it easily and you won’t have write lock issues.
See here for details:
http://www.touchlab.co/blog/single-sqlite-connection/
It links to a few blog posts of mine about Sqlite and multiple connections.