Reputation: 2056
My intuition says to do it once in onCreate()
, but I am not sure if there is some advantage to having a fresh instance each time. What's the best practice here?
Upvotes: 0
Views: 89
Reputation: 126445
Like Hojjat points out you should not re instantiate objects, you must create again the objects if they are not currently present,
if(myObject == null){
myObject = new ObjectFoo();
}
but if you are using a service maybe that will require the initialization:
class A extends Activity{
public ServiceClass mService = null; // service objecct
public void onCreate(){
mService = new ServiceClass();
}
public void onResume(){
mService.methodA();
}
}
Upvotes: 1
Reputation: 17498
We need some more context to give you a straight answer. Both methods might be called multiple times depending on what the user is doing.
I suggest defaulting your object instances as null, and inside onCreate()
and/or onResume()
, initialize it only if it is null.
if(objectInstance == null)
{
objectInstance = new MyObject();
}
Upvotes: 3
Reputation: 329
You should not re instantiate an object that you already have unless you have a reason for it! recreating objects just gets more memory and produces more garbage for the GC that is bad for efficiency!
So initialize needed objects in onCreate()
Upvotes: 1