I have a database-intensive app. Almost every activity requires access to the database, both reading and writing. I had a lot of problems with separate threads and activities on the stack closing connections to the database when the current activity was using it, even if I opened and closed the database immediately before and after use.
So I opted to use a single instance of the database. Now I have no problems--but is this right?
Application class
public class ApplicationClass extends Application
{
private DatabaseAdapter PrDatabaseAdapter;
public DatabaseAdapter getDatabaseAdapter()
{
return PrDatabaseAdapter;
}
@Override
public void onCreate()
{
super.onCreate();
PrDatabaseAdapter = new DatabaseAdapter(this);
PrDatabaseAdapter.open();
}
}
Adapter Class
The database adapter just sits on top of the DatabaseManager
(my SQLiteOpenHelper
)
private Context context;
private SQLiteDatabase db;
private DatabaseManager dbManager;
/**
* The DatabaseAdapter contains all interaction logic for the database
* @param context
*/
public DatabaseAdapter(Context context)
{
this.context = context;
}
/**
* Opens writable database
* @return DatabaseAdapter;
* @throws SQLiteException
*/
public DatabaseAdapter open() throws SQLiteException
{
dbManager = new DatabaseManager(context);
db = dbManager.getWritableDatabase();
return this;
}
/**
* Closes database connection
*/
public void close()
{
dbManager.close();
}
I'm still learning a lot about Java and Android and I would appreciate some insight to the pros and cons of this approach.