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 classandroid.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 { String globalVariable="My Global Variable"; }
- Add the class in AndroidManifest file as an attribute of <application> tag:
<application android:name=".MyApplication"
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="eyehunt.in.globalvariable"> <application android:name=".MyApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
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