Reputation: 47373
Is the following scenario a good practice and does it have any disadvantages or bugs?
One singleton DatabaseHelper
extending SQLiteOpenHelper
In my DAO
classes I call databaseHelper.getWritableDatabase()
which returns SQLiteDatabase
.
No manual close()
at all of DatabaseHelper
or any of the SQLiteDatabase
instances.
So this basically should maintain the connection through the lifetime of application. I think when the app is destroyed, the database connection will be automatically closed and resources freed. Also I think it is thread-safe.
Am I right?
Upvotes: 2
Views: 88
Reputation: 33505
One singleton DatabaseHelper extending SQLiteOpenHelper
Singleton design pattern is generally recommended way how to manipulate with SQLiteDatabase.
In my DAO classes I call databaseHelper.getWritableDatabase() which returns SQLiteDatabase.
Here i disagree. I would rather to create such a method(s) in SQLiteOpenHelper implementation class and just use these method(s) in DAO classes.
No manual close() at all of DatabaseHelper or any of the SQLiteDatabase instances.
This strongly depends on type of application but generally if you're not using database it should be always closed. Simplified said: When you will need to perform task, perform it and when all work is done close and release sources.
But we are talking about single-thread application. In multiple-thread (concurrent) application there are issues about accessing to one database from more threads at same time. SQLiteDatabase is not thread-safe by default (only if you are using ContentProvider which you don't. Maybe docs says something different but reality is somewhere else).
But here comes mechanisms like an usage of synchronized methods for reading and writing, synchronized blocks etc. so i think at beginning is enough to make method(s) properly synchronized and then after some tests makes improvements - gradually.
Your question takes "a lot space" also this problematic is very difficult and needs time for correct implementation - if you're doing on big project that can use thousands of people so here correct implementation of SQLiteDatabase as multi-thread is necessary.
Upvotes: 1
Reputation: 11211
I am using something similar to what you presented above. The difference is that I keep in the singleton the SQLiteDatabase
object and have wrapper methods for the CRUD
operations and synchronize the SQLiteDatabase
object in those so the user of the class won't have direct access to the SQLiteDatabase
object unless it is synchronized.
I am not sure if the method you use is thread safe since you didn't posted some code but if you don't use a synchronization mechanism then I suppose it isn't as I don't think that getWritableDatabase()
method does that for you.
EDIT
As Petar mentioned it seems that it is a default synchronization mechanism behind so I think the logic you are using should work fine.
Upvotes: 2