Skip to main content

Why shouldn't static variables be used as global variables in Android development


For mobile devices with small memories, memory usage and care of applications is essential. If an application uses images, it can easily result a memory leak if they cannot be collected by garbage collector. A reason why GB couldn't collect unused objects is that those objects refers to a static variable. So, if you are setting a property of a local variable with a static one, you need to be double careful.

This post which explains how to use static variables in an android app. To give a brief explanation about this fundamental way;  a local variable with a short life time and as a child of an object with big size(local var: textview, parent: activity) shouldn't refer to a static variable. This is because of that they will not be collected by garbage collector even if they are garbage and not used by the app. A few instance of activities in garbage can easily cause a memory leak in devices with small memories. It is also not very neat way for android development. So, avoid strong reference of static vars to such objects.

Using Static variables is a way of defining and using global variables as long as the app lives. But it is not very appropriate as it can result such disappointing endings. So, a question may come in minds: how should we define global variables? Which one is the best way? There are various ways to follow, but in my opinion, inheriting Application class and defining lifetime-long variables in it is the best one.

This is an example code of it.

public class MyApplication extends Application {

    private String var;

    public String getVar() {
        return var;
    }

    public void setVar(String pVar) {
        this.var = pVar;
    }
}
Application should use the newly implemented class instead of App class of Android library. To provide it, set name property of application tag in AndroidManifest.xml.

application android:name="MyApplication" android:icon="@drawable/icon" android:label="@string/app_name"
Because from each activity, application class is reachable, public methods of Application class can be easily called:

//set
((MyApplication) this.getApplication()).setVar("foo");  

//get      
String s = ((MyApplication) this.getApplication()).getVar();
It is quite perfect way to define variables whose lifetimes are same with the app.  I think this is a must-known way which is particularly essential for android development.

Thanks to Jeff in stackoverflow. This work is originated from this post.

Comments

Popular posts from this blog

Integration of MuPDF Project as a Library into an Android Studio Project

I have needed to use MuPDF library in my android project. After some research, I have seen that there are many integration tutorials but, but integrated projects are developed on Eclipse. For projects on AndroidStudio+Gradle, there is no example. I mean there is no specific example which exactly refers to this issue. So, after achieving my goal, I want to share the steps publicly so that it can be reused by others.

Migration from Proxmox to Openstack

I needed to migrate virtual machines in proxmox to openstack. VMs are in raw format. I needed to take some actions for a succesfull migration. I have perform all actions on Ubuntu 12.04 with virt-manager. qemu-kvm is installed. Here is the list of actions that I took: First, close the machine and copy the image file into your Ubuntu. Convert raw image to qcow2 format: qemu-img convert -O qcow2 image1.raw image1.qcow2 You need the image in qcow2 format for compatibility with openstack platform.  Open the converted image in virt-manager. Before opening, edit disk options. Under ' advanced options ' section, select ' qcow2 ' as ' storage forma t '. Start the virtual machine. You should see the login screen soon. (If you don't set storage format, vm will not find a bootable device. )   If everything is ok so far, close the vm. Take qcow2 image and upload it into glance. It may take time depending on size of it. After this process is completed, open a...

How to avoid API-level warning of Android Studio

Before giving the solution, let's start with a scenario. setSelectionFromTop() is a new method in Android Lollipop API. This method is basically beneficial to precisely keep scroll state of a ListView. By keeping that info, a developer can go back to old scroll state after doing some operation like data set change. You are aware of API level and you do your control before you call this function: if (currentapiVersion >= Build.VERSION_CODES.LOLLIPOP) { srlistview.setSelectionFromTop(index, top); } But if project minSdk is set to a lower level (in this case it is 15), this warning will still be displayed in Android Studio: