Reputation: 543
I'm new to android and fragments, so my question is this about the appropriate method to store values in the app database.
Calling a fragment from activity and passing the database handler?
ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
fragment.<specific_function_name>(dbhandler);
or calling an activity method from the fragment?
import mainActivity;
...
mainActivity currentActivity=(mainActivity )getActivity();
currentActivity.storeValures(val,val2...)
or just setting a database handler on every fragment?...
Or maybe there is a better design to deal with this?
Thanks in advance for your answers.
Upvotes: 0
Views: 62
Reputation: 224
Since database manager will be universal for the entire app, you can create a DataHandler class, that will have singleton Datahandler instance
public class MyDatabaseHandler extends SQLiteOpenHelper{
private static MyDatabaseHandler databaseHandlerInstance;
public static synchronized MyDatabaseHandler getInstance(Context context) {
if(databaseHandlerInstance == null)
databaseHandlerInstance = new MyDatabaseHandler(Context context);
return databaseHandlerInstance;
}
public MyDatabaseHandler(Context context){
// Call to super class
//
}
// ..... onCreate calls
}
This way you can use dbhandler from anywhere in your app like MyDatabaseHandler.getInstance(context)
I use this approach ...
Upvotes: 1