Aiming at performance, how should I instantiate an object (eg a DatabaseHandler) to be used in Fragments. Should I instantiate them in activity and pass via constructor method to Fragments or should I instantiate them in each Fragment?
Aiming at performance, how should I instantiate an object (eg a DatabaseHandler) to be used in Fragments. Should I instantiate them in activity and pass via constructor method to Fragments or should I instantiate them in each Fragment?
To know the best alternative, you would need to know if your object will be used by all the fragments.
If so, it would be interesting to create an abstraction common to all fragments (e.g.AbstractFragment
) that would implement a default constructor to initialize this object as an attribute of this abstraction, and make it accessible to all child fragments. So you do not repeat the declaration of the object in all the fragments. In this approach, the state of the object may vary from fragment to fragment (i.e., it is not a static
attribute) but its existence is common to all.
If the object belongs only to specific fragments, the ideal is to declare it within the scope of the same fragment. In this approach you would add it as an attribute initialized by the constructor or parameter of a method depending on the use of it within the fragment. If it is heavily used, it places it as an attribute, otherwise, as a parameter of the method that will use it. So you keep your classes cohesive.