In this example defining Variable in Application context and you can use this variable as a Global variable. You can set value in this variable and get value on any activity / broadcast recieiver / service in application context(environment).
In Further examples you will see good use of this way to follow SINGALTON pattern and MVC pattern in android.
In Further examples you will see good use of this way to follow SINGALTON pattern and MVC pattern in android.
The problem is how to save value across several Activities and all parts of your application context. You can achieve this by creating static variable but it is not the good way it influencing towards memory leaks. The way in Android is to associate your variable with the Application context.
Every Application has a context, and Android guarantees that Application context will exist as a instance across your application.
The way to do this is to create a Class and extends with android.app.Application, and specify your class in the application tag in your AndroidManifest.xml file. Android will create an instance of that class and make it available for your entire application context. You can get object of your class on any activity / broadcast reciever / service in application context(environment) by Context.getApplicationContext() method.
Every Application has a context, and Android guarantees that Application context will exist as a instance across your application.
The way to do this is to create a Class and extends with android.app.Application, and specify your class in the application tag in your AndroidManifest.xml file. Android will create an instance of that class and make it available for your entire application context. You can get object of your class on any activity / broadcast reciever / service in application context(environment) by Context.getApplicationContext() method.
Example WorkFlow :
Project Structure :
File : src/GlobalClass.java
Create your custom class subclass of android.app.Application class. you will use this class as global class for your Application environment(Conext).
package com.androidexample.globalvariable; import android.app.Application; public class GlobalClass extends Application{ private String name; private String email; public String getName() { return name; } public void setName(String aName) { name = aName; } public String getEmail() {
|