Using static variables in your Android project

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

. . .

Leave a Comment

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


2 comments

  • kinsley kajiva
    hey thank you for the tip
    • Anchit Makkar
      your welcome
  • css.php

    We've bought a Shopware Extension which is a hybrid App, which we can now offer in the Google Play Store and the IOS App Store. I'am still impressed how fast and how sharp the support team leads us through every process of the App-Store clarification. Very fast and useful response.

    Markus Walter

    Markus Walter

    Founder, Das Apartment Living

    Talk to Sales

    Global

    Live Chat
    Start a Project


      Message Sent!

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

      Back to Home