Using static variables in your Android project

Hello everyone,

While working on one of my projects i used static variables as any other person would do , as java provides with the ease to access them and they have a fixed memory location so they help in retaining the states of the variables.

But they also causes error that are hard to catch and debug.

"static fields are attached to the Class instance as a whole, which is in turn attached to the ClassLoader which loaded the class. the_instance would be unloaded when the entire ClassLoader is reclaimed. I am 90% sure this happens when Android destroys the app (not when it goes into the background, or pauses, but is completely shut down.)”

Also there will be number of issues regarding the memory just because of their scope.
Your project would response in unexpected manner if you have not used them properly.

In order to have a program exactly as responsive as you designed it to be , one should try to avoid using the static variables or should use static final variables.

But if in case you can’t use either of the above then you need to be extra cautious while using the static variables and also should initialise them as soon as your activity is created so that your activity retains the state of the static variables¬†¬†as you kept in mind while writing your piece of code.

I personally faced this issue when i was using static variables without initialising the same, this lead to the value retained when activity was created again and thus in that case the whole output changed and believe me it was really hard to get the exact cause for this unexpected behaviour.

For this all i needed to change was to initialise the static variables in the “onCreate” method of my activity and then everything went smooth.

Thanks,

Keep coding and keep sharing : )

. . .

Comments (2)

Add Your Comment

  • kinsley kajiva
    hey thank you for the tip
    • Anchit Makkar
      your welcome
  • css.php
    Hire Us!
    Brief us about your requirements and we'll get back to you.
    Woo! Hooy!
    We have just recieved your project brief and our expert will contact you shortly.
    Send Again
    Close