In my Android app I use the following code to access db:
public class DbHelper extends SQLiteOpenHelper {
/* ... */
}
public class DbManager {
private DbHelper helper = null;
public DbManager(Context context) {
helper = new DbHelper(context);
}
public void method1(bool cond) {
SQLiteDatabase db = helper.getReadableDatabase();
/* operate on db... */
if (cond) method2();
/* operate on db... */
db.close();
}
public void method2() {
/* see below */
}
}
method1 and method2 can be called independently from outside the class. In addition, there are situations where method1 must call method2.
In method2 I need a db instance, so I should call SQLiteDatabase db = helper.getReadableDatabase();.
This is ok if method2 is not called by method1. On the other hand, if I call it from method1, I create a db handle twice.
Is this ok?
I think I can avoid this situation this way:
public void method2(SQLiteDatabase db) {
SQLiteDatabase locDb;
if (db == null) {
locDb = helper.getReadableDatabase();
} else {
locDb = db;
}
/* ... */
if (db == null) locDb.close();
}
then in method1 I will use method2(db); while from outside I will use method2(null);
Does it all make sense? Or I should simply ignore the fact that i'm creating "nested" db instances? How does this impact on performances with higher "nesting" levels?