Reputation: 15108
HI i am using an application in that there is so many fragments all fragments are using database, I just want to know how to manage database open close in this situation
I have more than 10 fragments which are using database should i have to open close database for each fragment or should I have to open database once app start and then close at the end of application
if that possible then how please explain me
Upvotes: 0
Views: 262
Reputation: 2140
Yes both way you can do this as per your requirement if you want to open database throughout all fragment then open it in Parent Activity onCreate method and Close it to OnDestroy method.
Or
Open Database in onAttach method in fragment and close in onDetach method that's it...
Upvotes: 1
Reputation: 24723
You can simply create a Singleton helper which you can use throughout the lifecycle of the application as noted here.
public class DatabaseHelper extends SQLiteOpenHelper {
private static DatabaseHelper sInstance;
private static final String DATABASE_NAME = "database_name";
private static final String DATABASE_TABLE = "table_name";
private static final int DATABASE_VERSION = 1;
public static DatabaseHelper getInstance(Context context) {
// Use the application context, which will ensure that you
// don't accidentally leak an Activity's context.
// See this article for more information: http://bit.ly/6LRzfx
if (sInstance == null) {
sInstance = new DatabaseHelper(context.getApplicationContext());
}
return sInstance;
}
/**
* Constructor should be private to prevent direct instantiation.
* make call to static factory method "getInstance()" instead.
*/
private DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
}
Upvotes: 1