I understand that Android Activities have specific lifecycles and that onCreate should be overridden and used for initialization, but what exactly happens in the constructor? Are there any cases when you could/should override the Activity constructor as well, or should you never touch it?
I'm assuming that the constructor should never be used because references to Activities aren't cleaned up entirely (thus hampering the garbage collector) and that onDestroy is there for that purpose. Is this correct?
I can't think of any good reason to do anything in the constructor. You never construct an activity directly, so you can't use it to pass in parameters. Generally, just do things in onCreate.
A good reason for putting things in the constructor as Gili's comment had stated is the use of final fields.
However, if you initialize things in the constructor, then the lifespan of the object will be a little bit longer, though I don't think by much because the onCreate would be called shortly thereafter.
Although it's against my ideal, I do avoid the constructor for initialization of the activity members and rely on onResume() and onPause() for resources that my app is dealing with.
For onCreate() I usually use it to do view mapping to local variables. Though android-annotations already does that for me so I rarely have an onCreate() method for my Activity. I still use it in Service though.
However, if you look at the members you may be initializing
they would have a "close" method that you have to invoke at the proper time (onResume or onPause)
they would be part of the view which means it needs to be initialized then onCreate needs to be called
they are constants which don't need to be put in the constructor anyway, just a static final would do. This includes Paint and Path constants which can be initialized by a static block
I am now on a case that needs to override the constructor. In fact, I have some activities that have the same structure. So instead of creating many activities, I'll create one "Master" activity and the others will inherit this one. So I need to override the constructor of the child activity to be able to initialize some variables that will be used in the oncreate methods.
In two words, the constructor makes you simulate a "masteractivity" that can be reused by inheritance!
You need to override the Constructor when your activity will have custom params or you want to track calls from classes that inherited from.
Related
I am new to Android development, and somewhere I read that we shouldn't put a lot of code in onCreate(), because when running the application it will take more time.
So if I have 10 or 20 or ... UI elements (buttons, imageviews, ...) is it safe to use findItemById for all of them in onCreate or just find them in a method where we are going to use them? And what's the difference between an Override method and a regular method ?
There is no harm in getting reference to your UI elements in onCreate method it wouldn't effect your performance much. Defining in onCreate is beneficial because its the first method which will get executed and thus you will have reference to your view elements from the beginning.
Overriding means redefining the methods which were already defined in the class which you have inherited other methods are regular methods.
Method overriding, in object oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes.
please check this out for onCreate and other activity lifecycle method
http://developer.android.com/reference/android/app/Activity.html#onCreate(android.os.Bundle)
It doesn't seem as intuitive to decide which variables should be instance variables and which should be locally declared in classes that extend Activity to me as for other types of objects.
For classes that DO extend Activity, where do you declare the Views and ViewGroups, assuming declaring them both in the onCreate() method and as instance variables works. Which is the convention?
So classes that extend Activity aren't like the everyday objects we deal with where it's pretty easy to distinguish which variables should be instance variables and which should be locally declared.
Sure they are. Declare them where you need them. If you only need to access them in certain methods to say set text or something then declare them there. If you need them in multiple methods then declare them as member variables.
assuming declaring them both in the onCreate() method and as instance variables works.
Why would you declare them in two places?
Which is the convention?
See the first part of this answer. Typically I declare them as member variables and initialize them in onCreate() because I seem to need them in multiple places and I like having them in one place.
Just make sure you initialize them after calling setContentView() or they will be null.
Activity in Android represents part of UI object, lets say "window".
Activity has some components - layout with Views.
If you want to use your views in many methods of your activity class then declare them as instance variables. Because finding them with findViewById will be done only once. And then you can use them many times just by using instance variables.
If you make your views references local their scopes will be narrowed.
If the activity holds the Views/View groups it's recommended to declare them as private members in the activity class.
Simply as is :)
Are there any performance (or other) concerns on passing Activity as a method parameter? I need to define an image picker/cropper in a modular way (UtilClass) that can be used in several activities and I will need to make Activity-dependent calls.
Well there is no performance concern, since you will pass the memory address.
Take a look at this post please:
Is Android Context thread safe?
You should avoid keeping reference to activity after it closed, I see two ways: using WeakReference in Utility class or set activity reference to null in Utility class in onDestroy \ onPause method.
is it appropriate to define instance variables on the top of the class or we need to define them in onResume/onPause of the activity
Depends on the type of variable. There are some things (e.g. Views) that are not available until the layout is initialized. For others (e.g. resources) you need a Context so you'd have to wait until onCreate as well.
If you just want to define an integer or a String, namely, stuff that doesn't depend on the Android framework, go nuts.
If you are defining instance variables in your onResume method, then you are effectively re-assigning values to them everytime your Activity is resumed (and thus discarding any previous values). Define your instance variables in onCreate, which is called only once pr. Activity life-time.
I'm new to Android development and so far I have been mostly figuring out how to get tutorial code to work in an app I'm building. I am struggling in understanding where to declare variables and why I copy and paste some tutorials that end up with errors.
For example, I am trying to learn how to use the ViewFlipper. From this tutorial I have issues with Eclipse telling me that vf is not a variable when I use it inside OnClick. So when I move the line:
ViewFlipper vf = (ViewFlipper)findViewById(R.id.viewFlipper1);
to just above my OnCreate method, then it works. Why do I see so many tutorials with the variables declared in OnCreate and why doesn't it work for me? Where is the appropriate place to declare them? I understand the basics of encapsulation and inheritance, so is OnCreate just like any other method and any variables declared in there are isolated from other methods? What about my buttons, should I declare those inside my class but outside the OnCreate?
Why do I see so many tutorials with the variables declared in OnCreate and why doesn't it work for me?
Declaring variables within a method, or, outside, really boils down to what kind of scope you want to associate with the variable.
Inside a method, you need to be careful that you're declaring a variable before you intend to use it.
Where is the appropriate place to declare them?
Appropriateness of where to declare a variable depends entirely on where all you want to use it. Declaring a variable at the class level, when you only intend to use it within a method is unwise. And declaring variables within methods, when a lot many other methods in the class want to access it, and you end up passing the variables to each method - is also unwise. So for now, you can just consider:
Declare variables at class - when many methods in the class need to access it.
Declare variable in methods - when only the method has use for the variable.
I'd like to add, that 1 and 2 are not universal rules that can be applied blindly - but to get off to a start, you can follow them, until you figure out the deeper nuances associated with variable scoping, access specification and lifetime.
I'm not talking about access specifiers here, since, they merit a much detailed understanding, which you can get here. And neither have i talked about the difference of instance vs. class variables here, because you'd be better of referring to an official doc like this one.
I understand the basics of encapsulation and inheritance, so is onCreate just like any other method and any variables declared in there are isolated from other methods?
That's correct.
What about my buttons, should I declare those inside my class but outside the onCreate?
UI components in Android are typically required by multiple methods to access. TextView, Button, etc - usually have states which need to be altered at different times, from different methods - so you'd be better off declaring them at the class level.
Another important reason why you should prefer declaring UI variables at the class level is that you reduce the overhead of having the Android framework create them for every method invocation. As long as your Activity instance is alive, the framework holds onto the UI components/variables.
onCreate is just like any other method and all the java rules regarding encapsulation and variable scope apply to it. Declare the ViewFlipper variable as a class member, outside your onCreate method. But instantiate it inside your onCreate method, just as the tutorial says.
Everything in android works just as it does in java. All the programming rules of java are followed here.
this is because outside the onCreate method, variables are global to your class. Aka, any method in your class can access those variables. When you declare variables within onCreate, those variables are only accessible within the brackets of the oncreate method. You should declare your variable outside the onCreate method, and initialize them within the onCreate method:
ViewFlipper vf;
onCreate(....)
vf = (ViewFlipper) findViewById(R.id.viewFlipper1);
then set your onClickListener