Declare global variable in android Java Eclipse Studio

Defining + Making + Use Global variable inside android application development project step by step tutorial.

Global variables are used to make that type of variables which is accessible through multiple scopes in programs like single variable can use into multiple classes, function by declaring at one time. Global variables can be accessible after declaring them. So here is the complete step by step tutorial for Declare global variable in android Java Eclipse Studio.

How to Declare global variable in android Java Eclipse Studio.

  1. Creating another sub class named as Global_Variable.java .
  2. After creating class you have to add that specified class into AndroidManifest.xml file using android:name=”com.globalvariable_android_examples.com.Global_Variable” just after <application
    android:allowBackup=”true”
    android:icon=”@drawable/ic_launcher”
    android:label=”@string/app_name”
    android:theme=”@style/AppTheme”>
  3. After adding your class into Manifest file android application program will automatically creates instance of your class to use into whole application at any place by simply implementing Context.getApplicationContext() method.

Code for MainActivity.java file.

package com.globalvariable_android_examples.com;
import android.app.Activity;
import android.os.Bundle;


public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 Global_Variable GV = ((Global_Variable)getApplicationContext());
 String Global = GV.getState();
 
 }
}

Code for Global_Variable.java file.

 package com.globalvariable_android_examples.com;

import android.app.Application;

public class Global_Variable extends Application {

 private String GlobalString;

 public String getState(){
 return GlobalString;
 }
 public void setState(String GS){
 GlobalString = GS;
 }
 }

Code for AndroidManifest.xml file.

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

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

 <application
 android:allowBackup="true"
 android:icon="@drawable/ic_launcher"
 android:label="@string/app_name"
 android:theme="@style/AppTheme"
 android:name="com.globalvariable_android_examples.com.Global_Variable" >
 <activity
 android:name=".MainActivity"
 android:label="@string/app_name" >
 <intent-filter>
 <action android:name="android.intent.action.MAIN" />

 <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
 </activity>
 </application>

</manifest>

Declare global variable in android Java Eclipse Studio