Can't get SQLite writable database - android

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.

Related

opening and closing a sqlite database after using it everytime

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.

How to force serial/sequential execution of AsyncTasks in Android 2.x

There are a few Android APIs (after donut and before honeycomb) if Im not mistaken, where Google have enabled the AsyncTasks to run paralelly aiming for faster execution. Then lots of devs made mistakes when reaching out to the same database using multiple AsyncTasks, and since Android 3.0 AsyncTasks are running serially by default.
I am suffering this problem now when testing my app on an Android 2.3.4 device with my SQLite
First, Im getting categories from the server, I open DB, insert them close DB.
Second I get the subcategories from the server, open DB, insert them into DB, close DB
Third I get user items from the server, open DB, insert items, then close DB
Im taking good care to ensure that one starts after another, but in every 8-10 iterations something somewhere slows down and overlaps with another procedure right in the moment where a task is opening the db, another task closes it right after, and the first task starts trying to write to a closed db....
What do I do? I want clean, reliable separation, sequential execution and I dont want to start the asynctasks from the previous asynctask's onPostExecute, because these three will not always run in a row
I read an article yesterday that you CANT do it on android 2.x
Shall I try to open the DB and DBHelper before ALL of the operations and close the DB afterwards?
EDIT: Usually I get the error here (at Begin transaction):
(The error says that the DB is closed)
#Override
protected Void doInBackground(Void... arg0) {
// dbTools.close();
try {
if (database == null) {
database = dbTools.getWritableDatabase();
}
} catch (Exception e) {
e.printStackTrace();
}
ContentValues values = new ContentValues();
database.beginTransaction();
try {
// Iterating all UserItem objects from the LinkedHashSet and getting their info
for (UserItem userItem : userItems) {
// Inserting values for the database to insert in a new record
values.put(C.DBColumns.ITEM_ID, userItem.getItemId());
values.put(C.DBColumns.ITEM_NAME, userItem.getItemName());
// database.insertWithOnConflict(C.DBTables.ITEMS, null, values, SQLiteDatabase.CONFLICT_REPLACE);
database.insert(C.DBTables.ITEMS, null, values);
} // End of For loop
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
// Closing all cursors, databases and database helpers properly because not closing them can spring lots of trouble.
if (database != null && database.isOpen()) {
try {
database.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
} // End of doInBackground
And this is my DBTOOLS CLASS:
public class DBTools extends SQLiteOpenHelper {
// Its a good practice for DBTools to be a singleton. Do not instantiate it with "new DBTools(context)" but with
// DBTools.getInstance(context) instead
private static DBTools sInstance;
public static DBTools getInstance(Context context) {
if (sInstance == null) {
sInstance = new DBTools(context);
}
return sInstance;
}
public DBTools(Context context) {
super(context, C.Preferences.LOCAL_SQLITE_DATABASE_NAME, null, 1);
}
public void onCreate(SQLiteDatabase database) {
database.execSQL(SQLQueries.tableCategoriesCreate);
database.execSQL(SQLQueries.tableSubcategoriesCreate);
database.execSQL(SQLQueries.tableItemsCreate);
}
public void onOpen(SQLiteDatabase database) {
database.execSQL(SQLQueries.tableCategoriesCreate);
database.execSQL(SQLQueries.tableSubcategoriesCreate);
database.execSQL(SQLQueries.tableItemsCreate);
}
public void onUpgrade(SQLiteDatabase database, int version_old, int current_version) {
database.execSQL(SQLQueries.tableCategoriesDrop);
database.execSQL(SQLQueries.tableSubcategoriesDrop);
database.execSQL(SQLQueries.tableItemsDrop);
onCreate(database);
}
} // End of Class
Since you can't call from onPostExecute, I would say you have two options, one would be to move your open close calls to the beginning and end of your activity or service.
Option two would be to setup a reference counter in your DB and DBHelper where you track the number of times open has been called, and then decrement that count when close is called. That way you can perform close only when the count is 0. One thing to remember when taking this approach is that you should probably have a method that will force the db to close that you call when you are sure your other connections are done. This shouldn't be necessary but will be a failsafe to ensure the db gets closed if something goes wrong.
Edit: You would have to make DBTools a singleton for it to work, but it's not equivalent. Here's a quick example.
public class DBTools {
private static DBTools instance;
private static int openCount;
public DBTools getInstance() {
if (instance == null) {
instance = new DBTools();
}
return instance;
}
private DBTools() {
openCount = 0;
}
public void open() {
openCount++;
//Do open
}
public close() {
openCount--;
if (openCount == 0) {
//Do close
}
public void forceDBClose() {
//Do close
}
}
I am also a newbee in android. I was having a problem like this too.
To overcome this, i used Singleton class.
I created one instance of the DBHelper class and used it in all my asynctasks.
So, until the DB is closed, all the asynctasks access the initialised DB object.
If there is no object in the memory, the async tasks, instantiates it and use it then.

Android SQLite leaked Error

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.

Keeping a global reference to SQLiteDatabase?

I'm using a single sqlite database throughout my app. So I want to wrap a connection to the db in a singleton for convenience. At first I thought I could keep a reference to the SQLiteDatabase around for that:
MySQLiteOpenHelper helper = new MySQLiteOpenHelper(appContext); // local
myGlobalSQLiteDatabase = helper.getWritableDatabase(); // global
...
void someFunction() {
try {
myGlobalSQLiteDatabase.insertOrThrow(...);
} catch (Exception ex) {
}
}
but this would result in errors such as:
(1802) os_unix.c:30011: (2) stat(/data/data/com.me.test/databases/test.db) -
(1802) statement aborts at 16: [INSERT INTO mytable(f1,f2) VALUES (?,?)]
android.database.sqlite.SQLiteDiskIOException: disk I/O error (code 1802)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:775)
...
(this is all being done on the main thread, a single test).
My second attempt was to instead keep a global reference to the helper only:
myGlobalSQLiteOpenHelper helper = new MySQLiteOpenHelper(appContext); // global
...
void someFunction() {
SQLiteDatabase db = myGlobalSQLiteOpenHelper.getWritableDatabase();
try {
db.insertOrThrow(...);
} catch (Exception ex) {
} finally {
db.close();
}
}
and that works. I have to call getWritableDatabase() and close() on each call of someFunction().
I don't know how much overhead there is in getWritableDatabase() and close(), I was originally hoping for the fastest implementation possible, as I'll be calling someFunction() repeatedly in response to user input. Is the second method the best option for this setup?
Thanks
You don't need to write getwritable database again and again just make a constructor of db class public DBCustomer open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
and call all the function of db just decalring object and calling object.open function

leaving sqllite database open on android, bad idea?

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.

Categories

Resources