I have been learning (slowly but surely) how to do deal with sqlite databases on android systems. Using information I found here:
http://mfarhan133.wordpress.com/2010/10/24/database-crud-tutorial-for-android/
I have learned how to create, load things into and retrieve information from a database on my android system. One of the hitches was this method here:
public Cursor getClientsCursor() {
StudioTabOpenHelper dbAdapter=StudioTabOpenHelper.getDBAdapterInstance(this.getListView().getContext());
try {
dbAdapter.createDatabase();
} catch (IOException e) {
Log.i("*** select ",e.getMessage());
}
dbAdapter.openDataBase();
String query="SELECT * FROM CLIENTS;";
Cursor c = dbAdapter.selectRecordsFromDB(query, null);
//dbAdapter.close();
return c;
}
The problem was that the above code was closing the adapter I had opened...this was causing the part where I used that returned cursor to complain that database conn#0 already closed. So I commented out that dbAdapter.close(); I think this is bad in the future if i call this method again.
So my question is: Should I at the start of my application create the dbAdapter and open the database and leave it open and never close it? (how do i pass the dbAdapter around to activities, fragments etc if I go this route) ... or how can I use the getClientsCursor method as is and figure out some other way to pass back the cursor and be able to call the .close()?
/**
* Open the database
* #throws SQLException
*/
public void openDataBase() throws SQLException {
String myPath = DB_PATH + DATABASE_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
/**
* Close the database if exist
*/
#Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
My adapter code was gotten from here:
http://mfarhan133.wordpress.com/2010/10/24/database-crud-tutorial-for-android/
I just didn't call my class DBAdapter but called it StudioTabOpenHelper.
You may close your adapter on the
onDestroy() method of your activity.
Related
Is it a good practice to open and close the database for every database transaction operation? let me clear you more.
I have two methods like
public SQLiteDatabase getDatabase() {
if (database == null || !database.isOpen()) {
database = getWritableDatabase();
}
return database;
}
public void closeDatabase() {
if (database != null && database.isOpen()) {
database.close();
}
}
so every time, when I am updating/inserting or deleting, I am opening the database and closing it.
public void insert(...) {
getDatabase().insert(...);
closeDatabase();
}
public void update(...) {
getDatabase().update(...);
closeDatabase();
}
public void delete(...) {
getDatabase().delete(...);
closeDatabase();
}
remember that all these methods are inside a class DatabaseHelper which is extending SQLiteOpenHelper and there is a global variable private SQLiteDatabase database
and I will perform these operations(insert/update/delete) more frequently.
So my question is Is it a good practice to open and close database for every transaction? if not, what is the good way? Where and When I have to close my database?
Opening and closing the database every time may (un-intentionally) run into problem such as Trying to open an already closed database.
Hence, I would suggest is to have a Singleton for the creating the database object, so that every time you make a call to database = getWritableDatabase(); you refer to the same object.
Consider closing this in onDestroy() method, so that as and when the App closes database is closed too.
private static AllItemsDB db; //AllItemsDB is my database class
public static AllItemsDB getDb() {
if (db == null) {
Log.d("","Issue here");
db = new AllItemsDB(app);
Log.d("","Issue here not");
}
return db;
}
since this is a static method, I can do AllItemsDB.myCRUD_methods and it will return me the same oblect every time and easy to access as well. :)
Help.
I'm trying to implement android SQLite usage design pattern that ensures one opened SQLiteDatabase instance per application.
public class BaseDataSource {
private static final CustomSQLiteHelper dbHelper = CustomSQLiteHelper.getInstance();
protected static SQLiteDatabase database;
static {
//HERE RISES EXCEPTION
BaseDataSource.database = BaseDataSource.dbHelper.getWritableDatabase();
}
private void close() {
if(null != BaseDataSource.database && BaseDataSource.database.isOpen()) {
BaseDataSource.database.close();
if(null != BaseDataSource.dbHelper) {
BaseDataSource.dbHelper.close();
}
}
}
protected BaseDataSource() {}
protected void finalize () throws Throwable {
close();
super.finalize();
}
}
But while my applications starts I get this kind exception:
Caused by: java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/data/com.xxx/databases/xxx.db
How SQLiteDatabse database can be opened and closed before class was created?
UPDATED
I found my own bug. It was in CustomSQLiteHelper class. In onCreate method I closed database. I tried every soliution that I found in internet and due to that I made a bug.
if you going to event any thing then first need to open as write database. So for that use this method
and call like this
openAsWrite();
public void openAsWrite() throws SQLException {
db = DBHelper.getWritableDatabase();
}
// ---closes the database---
public void close() throws SQLException {
DBHelper.close();
}
Use following pattern when getting a database object:
try {
if (sDatabase != null) {
if (!sDatabase.isOpen()) {
sDatabase = sContext.openOrCreateDatabase(DATABASE_NAME, 0, null);
}
} else {
// open database here
sDatabase = sContext.openOrCreateDatabase(DATABASE_NAME, 0, null);
}
Log.d(TAG, "Database successfully opened.");
} catch (SQLException e) {
Log.e(TAG, "" + e);
}
Using database object as static makes your class behave like this.
Creates database instance when the class is loaded.
closes the database connection when finalize method is called.
your class will not going to acquire database connection anymore, and it will have the database instance which is closed already.
eventually when try to access the instance which is closed, it pops the error to you
I think you should use a different approach will be better.
I've got my database connection setup in an Application but LogCat keep's telling me about a SQLite leak
04-25 11:22:23.771: W/SQLiteConnectionPool(9484): A SQLiteConnection object for database '+data+data+com_appstart+databases+database' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
I'm starting to wonder if it is down to how I'm using the database adapter.
I attach my code...
This is my code where some times i found and error..
try{
DBAdapter dba = new DBAdapter(this);
dba.open();
Cursor c = dba.getModules(Constant.LANGUAGE_ID);
for (int i = 0; i < c.getCount(); i++) {
if (i > 2) {
a.add(c.getString(2));
moduleid.add(c.getString(0));
icon_name.add(c.getString(1));
System.out.println(c.getString(2) + "------" + c.getString(0));
}
c.moveToNext();
}
c.close();
dba.close();
}catch(Exception e){
e.printStackTrace();
}
this is my DBAdapter class that contains Open() and Close() methods.
public DBAdapter open() throws SQLException {
db = DBHelper.getWritableDatabase();
return this;
}
public void close() {
DBHelper.close();
}
What is this DBAdapter class you're using? I don't know what it's doing so I don't know if it's correct. You should check where the SQLiteConnection object is obtained that the error message refers to, and ensure that that SQLiteConnection is close()d.
Are you getting the error only occasionally or all the time? It's probably not the main problem you are observing, but your code also fails to call close() when there is an exception before the close(). You should ensure close() gets called regardless of exception path by guarding it with a try/finally block:
dba.open();
try {
Cursor c = ...;
try {
...
} finally {
c.close();
}
} finally {
dba.close();
}
Your problem is that you have to "Close" the database once you finished your database operation. So close your DB wherever you opened your DB.
in DBAdapter class, in close function replace DBHelper.close() from db.close();
public void close() {
DBHelper.close();
}
replace with the below;
public void close() {
db.close();
}
public DBAdapter open() throws SQLException {
db = DBHelper.getWritableDatabase();
//You should close the opened database
DBhelper.close
return this;
the same also goes for cursor once you opened it it needs to be closed.
I'm getting two contradicting Exceptions when creating and populating my new SQLiteDatabase in Android. In short my code:
SQLiteOpenHelper extending class:
public void onCreate(SQLiteDatabase db) {
db.execSQL(DB_TABLE_CREATE);
loadLevelData(db); //puts data in the database
//db.close(); <<< ?
}
In my activity class I instantiate this class (in onCreate()), and call getWritableDatabase():
dbHelper = new DbOpenHelper(getApplicationContext());
database = dbHelper.getWritableDatabase();
Now if I don't call db.close() after populating the database, like above, I get
android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
However if I DO close it, I get the following exception:
java.lang.IllegalStateException: database not open
on getWritableDatabase().
This really confuses me, so could anyone help me with what's wrong?
You are not expected to close the database in the DatabaseHelper class. However you need to close it every time you open it calling getWritableDatabase:
dbHelper = new DbOpenHelper(getApplicationContext());
database = dbHelper.getWritableDatabase();
//... do something with database
database.close();
You are closing your database at the wrong time.
I typically keep the database around like this:
public class MyActivity extends Activity {
SQLiteDatabase writeableDb;
// ...
// Code
// ...
public void onStart(){
super.onCreate(savedState);
// Do stuff, get your helper, etc
writeableDb = helper.getWriteableDatabase();
}
public void onStop(){
writeableDb.close();
super.onStop();
}
}
Alternatively, wrap all your code working with that db connection in a try/finally block
db = helper.getWriteableDatabase();
try { // ... do stuff ... }
finally { db.close(); }
Note: All of the opening/closing should be done in the Activity working with the database, not the open helper.
I've got custom adapter class, which incapsulates SQLiteDatabase. Adapter manages db connection:
public AutoDBAdapter(final Context context){
this.context=context;
checkDatabase();
try{
openDB();
}catch(Exception e){
e.printStackTrace();
}
checkDatabase()
method checks if DB exists and copies it from assets if necessary.
private void openDB() throws SQLException{
if(db==null)
db=SQLiteDatabase.openDatabase(dbFileName, null, SQLiteDatabase.OPEN_READWRITE);
}
I create AutoDBAdapter class inside my Activities.
I used this approach because I need my DB to be accessible from multiple activities. I know that that's not a good to do it.
My question: when should I close DB connection?
Any suggestions would be useful. Thanks.
If the db isn't used that often you should close it after each operation. If you are going to use it alot and want to keep it open, you should close it in the onPause method of the Activity.