Usage of SQLiteOpenHelper.getWritableDatabase - android

According to http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html#getWritableDatabase%28%29
Once opened successfully, the database is cached, so you can call this
method every time you need to write to the database.
Consider the following snippet:
SQLiteDatabase db1 = openHelperImplObj.getWritableDatabase();
// do something with db1
SQLiteDatabase db2 = openHelperImplObj.getWritableDatabase();
// do something with db2
db2.close();
// do something with db1
db1.close();
I presume the second call to getWritableDatabase() will return the same cached DB (the db1), wouldn't the line db2.close() cause any issue to db1 operations that happen afterward? If so, what is the recommended way to avoid such problem since the second call may happen anywhere, i.e. in a different function or even in different class.

When you open a data base by using db openHelperImplObj.getWritableDatabase();
then following thing check
1>If database is not created then it create database and open it for write mode else created first then open.
2>Second and most important what i have observed if data base is already created then it opened it but if its open already it do nothing, That means it occupy the old instance of data
base that open DB already until you close it.Thats why its better practice to close DB once it
use over
Hope you got

Related

Android: Create Database from SQL Script File WITHOUT Returning Data to Activity

I've done my homework; I know all the ways to query an SQLite db from an Activity.
The problem is that all the examples ASSUME that i want to "load" data from the db onto the FIRST Activity screen.
But when my app's FIRST Activity is loaded I DON'T WANT TO GET ANY DATA FROM THE DB; i just want to:
(1) Check if the db file has already been created (if the setup routines have already run).
(2) If the db exists, load the SECOND Activity (with ContentProvider/Loaders, etc.) so the user can start adding data.
OR
(2) If the db DOESN'T exist, WHILE STILL IN THE FIRST ACTIVITY run the setup routines (create the db/tables from an *.sql file & INSERT the dummy data where needed)...then load the SECOND Activity (with ContentProvider/ Loaders, etc.) so the user can start adding data.
To me, the simple operation of creating the db/tables shouldn't require all the OVERHEAD of a ContentProvider and a bunch of Cursors and Loaders.
Is there anybody who could point me to a SIMPLE solution? Thanks!
Yaqub's link was helpful...
...what i did was create public static final String arrays in a DBConstants class containing the commands to create the Database on first run.

How to over come database not opened exception?

I am implementing an app related to database.
So many times I am calling open and close database connection to insert, update and delete.
It is working fine.
But some times I am getting a database not opened exception in different situations.
How to solve these issues?
Well unless you put proper exception handling you would never know what causes this.
However a good idea is to adopt good ORM mapper for SQL Light with Android and this will improve your database interactions and exception handling and opening and closing it efficiently.
You can opt for SUGAR or ORMLight if you wish; In my opinion this should help you to fix your problem.
Based on the information you provided I can assume that the problem is in your business logic and nobody but you should be able to tell you the root cause.
Without your code here, we won't be able to point you to exact place.
One of the possible reasons can be that by your business logic you are trying to do some operation (insert, update whatever) on closed database.
You can do some workaround to try to ensure that your DB is always open when it is needed. If you implement database getter method with so called lazy initialization approach it will guarantee at least, that the DB is open when you need to access it.
Here is what I am talking about:
1. make a public method which supposed to return DB object:
public SQLiteDatabase getDB() {
if ((mDataBase == null) || (!mDataBase.isOpen())) {
// create or open your database using an OpenHelper
mDataBase = SQLiteOpenHelper.getWritableDatabase();
}
return mDataBase;
}
Now, everywhere in your code use this method to access the DB instead of directly accessing a variable mDataBase.
Note that the code is just to give you an idea and not actually compilable.
Still, I would recommend you to fix your business logic instead of using this workaround.

"database not open" when db is closed by different writer

I have many Fragments in a ViewPager in my app. At the start of the application three of them try to connect to database to retrieve data.
For database handling I use a singleton pattern with SQLiteOpenHelper. When I need my database I call it like this: SQLiteDatabase db=DatabaseHelper.getInstance(this.getContext()).getWritableDatabase();.
The problem:
If I don't close the db with db.close() I get a android.database.sqlite.DatabaseObjectNotClosedException of course. So I do.
But as it's a singleton approach, when one of my Fragments finishes to fetch the data, it closes the database and the rest of Fragments can't use it.
Checking if the databse is open on every iteration when I read something from it seems very redundant. What else can I do?

android sqlite database already closed error

I have an app with a sqlite database.
I created my own database class that holds an instance of SqliteDatabase . The class implements my queries, open, close, etc. (the class is NOT a singleton).
I have an activity, a service and an appwidget in my app.
Where I need the database, I create an object of my class, open , do stuff and close at the end.
for example in the activity I open the db in onStart and close it onStop.
Everything works great except in the appwidget.
If I need to select data in the appwidget onUpdate, then it's ok.
but when I try to do an UPDATE from the appwidget, I get the "database DATABASE_FLE already closeed" error.
What can it be?
I added some logs where I'm closing the db, and non of those lines execute before this error.. the db should be ok.
Any ideas?
Thanks.
What i am thinking about, is case in which android may close/unload your activity (this may happend for example if there is a little memory left on the device), but in this time your appwidget is still active.
Now, because of your activity is closed, hence you db is closed.
Appwidget tryes to update DB but its is already closed.
Check this scenario but anyway you should take this scenario in consideration. :)
The problem was that I compiled an SQLiteStatment object and saved it for future uses, while my database object got replaced..
so SQLiteStatement needs to re-compile again.
I had something like this:
public void func(SQLiteDatabase db) {
if (mStatement == null)
mStatement = db.compileStatement(SQL);
mStatement.execute();
The problem with this is that the db object changed in the function call, and the first db object that compiled statement was already closed.
The solution was to remove the if-null, and to compile the statement for every db object.

Resetting or refreshing a database connection

This Android application on Google uses the following method to refresh the database after replacing the database file with a backup:
public void resetDbConnection() {
this.cleanup();
this.db =
SQLiteDatabase.openDatabase(
"/data/data/com.totsp.bookworm/databases/bookworm.db",
null, SQLiteDatabase.OPEN_READWRITE);
}
I did not build this app, and I am not sure what happens.
I am trying to make this idea work in my own application, but the data appears to be cached by the views, and the app continues to show data from the database that was replaced, even after I call cleanup() and reopen the database. I have to terminate and restart the activity in order to see the new data.
I tried to call invalidate on my TabHost view, which pretty much contains everything. I thought that the views would redraw and refresh their underlying data, but this did also not have the expected result.
I ended up restarting the activity programmatically, which works, but this seems to be a drastic measure. Is there a better way?
Agreed with Pentium10, at least conceptually.
The application is using a Cursor to show its data. A Cursor in Android is akin to a client-side cursor in ODBC, in that it is a cached copy of all of the data represented by the query's result set.
Now, the normal way of handling changes in the database contents is to call requery() on the Cursor. That will ripple its changes through the CursorAdapter to attached ListViews or other AdapterViews.
In your case, I am not completely certain that will work, since you are closing, replacing, and re-opening the database. That should not be done with an open Cursor on the data, AFAIK. So, in your case, you'd need to close the Cursor, do the database shuffle, then run the query again to get a fresh Cursor on your new database.

Categories

Resources