In some cases during development android application you need define global variable.

What is Global Variable?

Global Variable is hold the value until your application is not destroyed. So you can access those variable across the application.

How to define Global variable in android?

You can extend the base android.app.Application class and add member variables. Android Application is Base class for maintaining global application state. Application class is first instantiated, when application launch and other classes process when  application/package is created.

  • Create Android application
  • Create new class “MyApplication.java”
  • Extend MyApplication.java by Application class and define variable.

  • Add the class in  AndroidManifest file as an attribute of <application> tag:

  • Then we can access your global data or variable from any Activity by calling getApplication()

Note : In Android Application is no need to application subclass , normally in most situation you can use static singletons. Here is office link for Application class.

Leave a Reply