I have a central database in my application that a few different activities need to access.
Should I share this object by making it static? Like for example in the activity that initializes the DB I do this:
protected static appDatabase db;
Then others can access it via FirstActivity.db
.
Another option is to create private appDatabase db
objects in every activity that needs it, but I suspect opening multiple db objects to access the same stored data may be wasteful.
However I don't know too much about java which is why I'm asking - what's the preferred way to do this, and why?
Thanks
You can use singleton like this;
private static DataHelper singleton;
public static DataHelper getDataHelper(Context context) {
if (singleton == null) {
singleton = new DataHelper(context);
OpenHelper openHelper = new OpenHelper(singleton.context);
singleton.db = openHelper.getWritableDatabase();
}
if(!singleton.db.isOpen()){
OpenHelper openHelper = new OpenHelper(singleton.context);
singleton.db = openHelper.getWritableDatabase();
}
singleton.context = context;
return singleton;
}
private DataHelper(Context context) {
this.context = context;
}
And call your singleton class like this;
public DataHelper dh;
this.dh = DataHelper.getDataHelper(this);
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