Issue
I have an activity which features 2 fragments. Both of them use the database helper created by the activity. One of the fragments also create a custom list adapter which also uses the helper.
Now my question is should each of these elements (activity, fragments, adapter) have their own helper created or can/should they share the one created by the activity?
Perhaps my approach is a bad one, what would you suggest then?
Here's where (on my activity) I'm instantiating the helper at the moment (onRestart is needed because onStart needs DB access too) :
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbHelper = new DBHelper(this);
}
@Override
protected void onRestart() {
super.onRestart();
if (dbHelper == null)
dbHelper = new DBHelper(this);
}
@Override
protected void onResume() {
super.onResume();
if (dbHelper == null)
dbHelper = new DBHelper(this);
}
@Override
protected void onPause() {
super.onPause();
dbHelper.close();
dbHelper = null;
}
Solution
Alex Lockwood recommends using a singleton - I tried to follow his approach and it simplifies the set up. There is no need to close the DB with each fragment. You can call it in each onCreate.
Answered By - user3460486
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.