Sunday 30 October 2011

How to Avoid Static Variables in Android

,

One of the best practice in coding is to avoid static variables wherever possible. This post help you to code without using static variables.
How can we avoid static variables in Android?

In Android, static variables can be avoided using a class extended from Application class as shown below. Inside the class using get – set method you can define your variables.


import android.app.Application;
import android.content.Context;

public class AppCommons extends Application {
 
 private Context _bgServiceContext;
 
 public void setServiceContext(Context bgServiceContext){
  _bgServiceContext = bgServiceContext;
 }
 
 public Context getServiceContext(){
  return _bgServiceContext;
 }
}

Now, in the Manifest file modify the application tag by inserting a new attribute name, with your new class name extended from Application class.

application android:="" android:label="@string/app_name" android:name=".AppCommons" icon="@drawable/icon"

Since for an application there will be only one Application object, you can always get and set the custom application object’s variables anywhere from your application as follows.

((AppCommons)getApplication()).setServiceContext(this);
((AppCommons)getApplicationContext().getServiceContext();

The application object’s life time is throughout the application’s life (and so your custom application object’s) and using the get(), set() method you can manage its data members, and finally you avoided a static variable in your application. J J J


Cheers,
Have a nice day. View Complete List of Tips

2 comments to “How to Avoid Static Variables in Android”

  • 31 October 2011 at 11:31
    Sreekanth says:

    Nice post. But why is it that we need to avoid static variables in Android? Any specific reason?

    delete
  • 31 October 2011 at 21:35

    Yes. Its always a good practice to avoid static variables from the application. Although the scope of the static variable is the life time of the application, its not necessary that they will get released from the memory even after exiting the application. But, when you implement a custom application object instead of static variables, it is guaranteed that it will be destroyed once we exit the application.

    delete

Post a Comment

 

Tips for Android Developers Copyright © 2011 -- Powered by Blogger