65.9K
CodeProject is changing. Read more.
Home

Global Variable in Android

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.86/5 (4 votes)

Jun 26, 2013

CPOL
viewsIcon

172616

This tip will help you to develop global variable in Android application.

Introduction

When we need to have several variables across applications, we can go for global variable. Here, I am going to explain, defining global variable by extending the Android's Application class. This is the base class for maintaining global application state.

Steps for Declaring Global Variable

  1. Create a class that extends the Application class:
    public  class  Global extends Application {
        private Boolean _notification=false;
        public Boolean get_notification() {
            return _notification;
        }
        public void set_notification(Boolean _notification) {
            this._notification = _notification;
        }
    } 
  2. Add the class to the AndroidManifest file as an attribute of <application> tag:
     <application
    android:name=".Global"
            .... />  
  3. You can access it from any context using the Context.getApplicationContext() method. Now, we can access the global data across the application like:
     Global global;
        public void onCreate(Bundle savedInstanceState) {
            global=((Global)getApplicationContext());
            Boolean notification=global.get_notification();} 

History

  • 26th June, 2013: Initial post

This tip is based on the following blog: