I have a newbie question about sqlite databases in android:
Do I really need to retrieve a writeable database everytime I manipulate data?
So can I write a DAO like this:
class Dao {
private final SQLiteDatabase database;
public Dao(SQLiteOpenHelper databaseHelper){
database = databaseHelper.getWritableDatabase();
}
public void insert(...){
ContentValues cv = new ContentValues(4);
database.insertOrThrow(TABLE, null, cv);
...
}
public void update(...){
ContentValues cv = new ContentValues(4);
database.update(....);
}
}
or do I must write my dao like this:
class Dao {
private final SQLiteOpenHelper databaseHelper;
public Dao(SQLiteOpenHelper databaseHelper){
this.databaseHelper = databaseHelper
}
public void insert(...){
SQLiteDatabase database = databaseHelper.getWritableDatabase();
ContentValues cv = new ContentValues(4);
database.insertOrThrow(TABLE, null, cv);
...
}
public void update(...){
SQLiteDatabase database = databaseHelper.getWritableDatabase();
ContentValues cv = new ContentValues(4);
database.update(....);
}
}
If the second approach is the correct one: do I also need to close the database after every operation:
public void update(...){
SQLiteDatabase database = databaseHelper.getWritableDatabase();
ContentValues cv = new ContentValues(4);
database.update(....);
database.close();
}
I guess its the same for databaseHelper.getReadableDatabase()
right?
You should close every cursor you open. But the database instance doesn't need to be closed after each use.
I usually fetch a writable database in onCreate()
and store the resulting SQLiteDatabase
as a member variable for each activity, and never explicitly close that instance. (But again, I do close every cursor as soon as I'm finished processing their results.)
See Managing SQLite Connections in Android for a little more discussion on the subject.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With