Wednesday, 26 June 2013

How to declare a Global variable in Android.





When we need to have several variables across application 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.



1) Create a class that extends 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"
                                .... />
Android will automatically create an instance of that class and make it available for your entire application.
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();}

6 comments:

  1. This is the base class for maintaining Moviles android baratos global application state.
    1) Create a class that extends Application clas

    ReplyDelete
  2. classic article. Really helpful.

    thanks

    ReplyDelete
  3. Thank you so much for this wonderful and helpful article.

    kind regards,
    SANI HYNE (delickate)

    ReplyDelete
  4. Thank you so much for sharing this worth able content with us. The concept taken here will be useful for my future programs and i will surely implement them in my study. Keep blogging article like this.
    Android Online Training

    ReplyDelete
  5. I simply want to say I’m very new to blogs and actually loved you’re blog site. Almost certainly I’m going to bookmark your blog post . You absolutely come with great well written articles. Thanks a lot for sharing your blog. Selenium Training in Chennai | Salesforce Training in Chennai

    ReplyDelete