Simulator Screenshots

Global Variable Or Application Context Variable - Android Example

DOWNLOAD SOURCE CODE
 

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.

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.

 

Example WorkFlow :

Global_variable_workflow

 

Project Structure :

 

Global_application_context_project_sketch

 

 

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() {
		
		return email;
	}
	
	public void setEmail(String aEmail) {
	   
	  email = aEmail;
	}

}

 

File : AndroidManifest.xml

 

Assign GlobalClass.java in application tag, see this line in application tag android:name="com.androidexample.globalvariable.GlobalClass"
After assign you can get GlobalClass.java instance on any activity / broadcast reciever / service in application context.

 


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidexample.globalvariable"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="9" />

    <application
        android:name="com.androidexample.globalvariable.GlobalClass"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.androidexample.globalvariable.FirstScreen"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            
        </activity>
        
        <activity android:name=".SecondScreen" ></activity>  
        <activity android:name=".ThirdScreen" ></activity>
    </application>

</manifest>

 

File : src/FirstScreen.java

 

getApplicationContext() method of Context will give GlobalClass.java instance and set name/email values and maintain state of GlobalClass.java instance.

 


package com.androidexample.globalvariable;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.app.Activity;
import android.content.Intent;

public class FirstScreen extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.firstscreen);
		
		final Button secondBtn = (Button) findViewById(R.id.second);
		
		// Calling Application class (see application tag in AndroidManifest.xml)
		final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
		
		//Set name and email in global/application context
		globalVariable.setName("Android Example context variable");
		globalVariable.setEmail("xxxxxx@aaaa.com");
		
		
		secondBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				
				Intent i = new Intent(getBaseContext(), SecondScreen.class);
				startActivity(i);
			}
		});	
	}	
}

 

File : src/SecondScreen.java

 

Call getApplicationContext() method of Context and get GlobalClass.java instance , By GlobalClass.java instance you can get set values for name/email variables.

 


package com.androidexample.globalvariable;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class SecondScreen extends Activity {
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.secondscreen); 
    
		TextView showGlobal     = (TextView) findViewById(R.id.showGlobal);
		final Button thirdBtn = (Button) findViewById(R.id.third);
		
		// Calling Application class (see application tag in AndroidManifest.xml)
		final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
		
		// Get name and email from global/application context
		final String name  = globalVariable.getName();
		final String email = globalVariable.getEmail();
		
		String showString = "

Name : "+name+"
"+
		                    "Email : "+email+"

";
		
		// Show name/email values in TextView
		showGlobal.setText(showString);
		
		thirdBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				
				Intent i = new Intent(getBaseContext(), ThirdScreen.class);
				startActivity(i);
			}
		});
		
	} 
	
	@Override
    protected void onDestroy() {
		
        super.onDestroy();
        
    }
}


 

File : src/ThirdScreen.java

 

Call getApplicationContext() method of Context and get GlobalClass.java instance , By GlobalClass.java instance you can get set values for name/email variables.

 


package com.androidexample.globalvariable;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class ThirdScreen extends Activity {
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.thirdscreen); 
    
		TextView showGlobal     = (TextView) findViewById(R.id.showGlobal);
		
		// Calling Application class (see application tag in AndroidManifest.xml)
		final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
		
		// Get name and email from global/application context
		final String name  = globalVariable.getName();
		final String email = globalVariable.getEmail();
		
		String showString = "

Name : "+name+"
"+
        "Email : "+email+"

";
		
		// Show name/email values in TextView
		showGlobal.setText(showString);
		
	} 
}

 

Share this: