Use a single Database Access Object attached to the ApplicationContext to handle the SqliteAssetHelper implementation, use getInstance() rather than using the DAO constructor for each connection, make sure you open and close the connection once in your apps life cycle and you can query the database as much as you like during the apps life cycle, also it avoids memory leaks.
/**
* Private constructor to avoid object creation from outside classes.
*
*/
private Databa
seAccess() {
this.masterOpenHelper = DatabaseOpenHelper.getInstance( "master.db");
this.dictionaryOpenHelper = DatabaseOpenHelper.getInstance( "dictionary.db");
isAlreadyOpen = false;
}
/**
* Return a singleton instance of DatabaseAccess.
*
* @return the instance of DabaseAccess
*/
public static DatabaseAccess getInstance() {
if (instance == null) {
instance = new DatabaseAccess();
instance.open();
}
return instance;
}
/**
* Open the database connection.
*/
public void open() {
this.masterDatabase = masterOpenHelper.getWritableDatabase();
Log.i(TAG, "master db is opened " + masterDatabase.isOpen());
this.dictionaryDatabase = dictionaryOpenHelper.getWritableDatabase();
Log.i(TAG, "dictionary db is opened " + dictionaryDatabase.isOpen());
isAlreadyOpen = true;
}
/**
* Close the database connection.
*/
public void close() {
if (masterDatabase != null) {
this.masterDatabase.close();
Log.i(TAG, "masterdb closed " + !this.masterDatabase.isOpen());
}
if(dictionaryDatabase != null) {
this.dictionaryDatabase.close();
Log.i(TAG, "dictionary closed " + !this.dictionaryDatabase.isOpen());
}
instance = null;
}
SqliteAssetHelper object
public class DatabaseOpenHelper extends SQLiteAssetHelper {
private static final String TAG = "DatabaseOpenHelper";
public static String DATABASE_NAME;
private static final int DATABASE_VERSION = 1;
private static DatabaseOpenHelper masterDb, dictionaryDb;
private DatabaseOpenHelper(String name) {
super(MyApp.mContext.get(), name, null, DATABASE_VERSION); // mContext is a WeakReference object
DATABASE_NAME = name;
}
public static synchronized DatabaseOpenHelper getInstance(String name) {
switch (name){
case "master.db":
if(masterDb == null)
masterDb = new DatabaseOpenHelper(name);
return masterDb;
case "dictionary.db":
if(dictionaryDb == null)
dictionaryDb = new DatabaseOpenHelper(name);
return dictionaryDb;
default:
Log.i(TAG, "database not found " + name);
return null;
}
}