- How to declare global variables in Android?
- Create Android global variable in Android Studio
- What is the Global Variable?
- How to define an Android Global variable in Android studio?
- Глобальная переменная или переменная контекста приложения — Android
- Файл : src/GlobalClass.java
- Файл : AndroidManifest.xml
- Файл : src/FirstScreen.java
- Файл : src/SecondScreen.java
- File : src/ThirdScreen.java
- Global Variable Or Application Context Variable — Android Example
- Example WorkFlow :
- Project Structure :
- File : src/GlobalClass.java
- File : AndroidManifest.xml
- File : src/FirstScreen.java
- File : src/SecondScreen.java
- File : src/ThirdScreen.java
How to declare global variables in Android?
This example demonstrates How to declare global variables in Android?
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
In the above code, we have taken text view to show global variable.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity < TextView actionEvent; @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); actionEvent = findViewById(R.id.actionEvent); actionEvent.setText("Click"); actionEvent.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View v) < singleToneClass singleToneClass = com.example.myapplication.singleToneClass.getInstance(); singleToneClass.setData("Tutorialspoint.com"); actionEvent.setText(singleToneClass.getData()); >>); > >
Step 4 − Add the following code to src/singleToneClass.java
package com.example.myapplication; public class singleToneClass < String s; private static final singleToneClass ourInstance = new singleToneClass(); public static singleToneClass getInstance() < return ourInstance; >private singleToneClass() < >public void setData(String s) < this.s = s; >public String getData() < return s; >>
Let’s try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project’s activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Now click on textview, it will show the result as shown below –
Click here to download the project code
Create Android global variable in Android Studio
In some cases, during development android application you need to define Android global variable. In this tutorial, you will learn how to define a global variable in Android.
What is the Global Variable?
Global Variable is holding the value until your application is not destroyed. So you can access those variables across the application.
How to define an Android Global variable in Android studio?
You can extend the base class android.app.Application and add member variables. Android Application is the Base class for maintaining a global application state. Application class is instantiated first when application launch and other classes process when application/package is created.
- Create an Android application
- Create a new class “MyApplication.java”
- Extend MyApplication.java by Application class and define a variable.
package eyehunt.in.globalvariable; import android.app.Application; public class MyApplication extends Application
Then we can access your global data or variable from any Activity by calling getApplication()
package eyehunt.in.globalvariable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; public class MainActivity extends AppCompatActivity < @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MyApplication application=(MyApplication)getApplication(); String globalVarValue=application.globalVariable; Toast.makeText(MainActivity.this,globalVarValue,Toast.LENGTH_LONG).show(); >>
Note: In Android Application is no need to application subclass, normally in most situation you can use static singletons. Here is office link for Application class.
Bouns: Kotlin is the official language of android , we suggest must adopt a new language and follow this tutorial : How to Declare a Global Variable in Android Kotlin
Глобальная переменная или переменная контекста приложения — Android
Объявив переменную в контексте приложения вы можете использовать её в качестве глобальной переменной. Вы можете задавать ей значение и получать из неё значение в любом месте приложения ( activity / broadcast recieiver / service ) из контекста приложения.
Используя этот способ, становится проще следовать шаблону SINGLETON и шаблону MVC в android.
Здесь показано решение проблемаы, заключающейся в том, как сохранить значение (переменной) проходя через несколько Activity и во всех других частях вашего приложения. Кончно Вы можете добиться этого, создав статическую переменную, но это приведёт к утечке памяти. Путь в Android — связать вашу переменную с контекстом приложения.
Каждое приложение имеет контекст, и Android гарантирует, что Application context будет существовать как экземпляр в любом месте вашего приложения.
Чтобы сделать это — надо создать класс, порождённый от android.app.Application и указать свой класс в теге Application в вашем файле AndroidManifest.xml. Android создаст экземпляр этого класса и сделает его доступным для всего контекста приложения. Вы можете получить объект своего класса в любом месте приложения (activity / broadcast reciever / service) используя метод Context.getApplicationContext().
Файл : src/GlobalClass.java
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; >>
Файл : AndroidManifest.xml
Определим GlobalClass.java в application теге, внимание на строку в теге application android:name=».GlobalClass» После этого экземпляр класса GlobalClass.java будет доступен в любом месте приложения ( activity / broadcast reciever / service ) в виде контекста приложения.
Файл : src/FirstScreen.java
Метод getApplicationContext() возвращает экземпляр класса GlobalClass.java. Далле присваиваются значения полям name/email в экземпляре GlobalClass.java класса.
package . your packagename . ; 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); >>); > >
Файл : src/SecondScreen.java
Метод getApplicationContext() возвращает Context в виде экземпляра GlobalClass.java класса, через который вы можете получать/задавать значения полям name/email этого экземпляра GlobalClass.java.
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
Метод getApplicationContext() возвращает Context в виде экземпляра GlobalClass.java класса, через который вы можете получать/задавать значения полям name/email этого экземпляра GlobalClass.java.
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); > >
Global Variable Or Application Context Variable — Android Example
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 :
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() < 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.
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); >>