Using static variables in your Android project

Updated 25 December 2016

Save

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 : )

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


2 comments

  • kinsley kajiva
    • Anchit Makkar
  • Start a Project


      Message Sent!

      If you have more details or questions, you can reply to the received confirmation email.

      Back to Home