Variables globales

Application class is the object that has the full lifecycle of your application. It is your highest layer as an application. example possible usages:

  • You can add what you need when the application is started by overriding onCreate in the Application class.
  • store global variables that jump from Activity to Activity. Like Asynctask.

    Sometimes you want to store data, like global variables which need to be accessed from multiple Activities – sometimes everywhere within the application. In this case, the Application object will help you.

    For example, if you want to get the basic authentication data for each http request, you can implement the methods for authentication data in the application object.

    After this,you can get the username and password in any of the activities like this:

    MyApplication mApplication = (MyApplication)getApplicationContext();
    String username = mApplication.getUsername();
    String password = mApplication.getPassword();

    And finally, do remember to use the Application object as a singleton object:

     public class MyApplication extends Application {
        private static MyApplication xxx;
    
        public MyApplication getInstance(){
            return singleton;
        }
        @Override
        public void onCreate() {
            super.onCreate();
            singleton = this;
        }
    }

    Fore more info. Please Click this LINK

You can create the global variable in android by declaring them in the class which extend the Application class.

Something like this.

class MyAppApplication extends Application {

    private String mGlobalVarValue;

    public String getGlobalVarValue() {
        return mGlobalVarValue;
    }

    public void setGlobalVarValue(String str) {
        mGlobalVarValue = str;
    }
}

MainActivity.java

class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle b){
        ...
        MyAppApplication mApp = ((MyAppApplication)getApplicationContext());
        String globalVarValue = mApp.getGlobalVarValue();
        ...
    }
}

Références :

https://androidresearch.wordpress.com/2012/03/22/defining-global-variables-in-android/

Publicités
Articles récents
Commentaires récents
fatima dans Bienvenue !
AdminDroid dans Bienvenue !
fatima dans Bienvenue !
Archives
Catégories
%d blogueurs aiment cette page :