Reputation: 14678
I just want to see what you guys might think the difference (in terms of usage, efficiency, or even good practice) with regard to android development.
If I use a static variable in one of my base activity (so its single instance and be access everywhere), as opposed to using a non static variable in my application subclass (which is a single application class for all the activities).
Both will achieve the same end results if you try to use a global variable.
I was using the static one then I moved to use the application subclass (in case you guys wonder "what is it I am using for", I wanted to play background music and control it from everywhere and I don't wish to use service for certain reasons).
Any help clarifying the best way to ?
Upvotes: 0
Views: 1806
Reputation: 67296
It depends on use also, suppose if you are using
android:process
for some reason in your Activity
or anything else in your Manifest file your static value will be reset and you will get the initial value assigned to static variable. In that case you can use SharedPreference
or Application
class.
Because if you use android:process
for any particular Activity then that Activity will run in another process and as we know that in Android every Application runs in its own process.
Other than this I don't see there is much issue using static. But, personally I would prefer Application
class as Android has it for global variables.
Upvotes: 3
Reputation: 29670
During the execution of a program, each variable has its own time within which it can be accessed. This is called the lifetime of the variable.
Instance variables: Instance variables are class members. Every time you create an object from a class, a brand new copy of these instance variables is created for this object. Actually, creating an object from a class means, partially, creating copies of instance variables for that object. So each object has its own copy of instance variables which exist as long as the object they belong to exists. The values of these variables constitute what we call: the state of the object.
Static variables: Static variables are also members of a class but can't belong to any object created from that class. So created objects from the class don't get their own copies of static variables. Therefore static variables are created only when the class is loaded at runtime. The existence of static variables is dependent only on the class itself. As a result, a static variable exists as long as its class exists.
One of main difference between these two variable is that when you are calling System.gc();
your instance variable is set to null while static variable will never set to null by calling gc.
Upvotes: 1