Android global variable
You can extend the base android.app.Application
class and add member variables like so:
public class MyApplication extends Application {
private String someVariable;
public String getSomeVariable() {
return someVariable;
}
public void setSomeVariable(String someVariable) {
this.someVariable = someVariable;
}
}
In your android manifest you must declare the class implementing android.app.Application (add the android:name=".MyApplication"
attribute to the existing application tag):
<application
android:name=".MyApplication"
android:icon="@drawable/icon"
android:label="@string/app_name">
Then in your activities you can get and set the variable like so:
// set
((MyApplication) this.getApplication()).setSomeVariable("foo");
// get
String s = ((MyApplication) this.getApplication()).getSomeVariable();
How to implement global variables in extends different from 'Application' and 'Activity'?
You can create a static instance of Globals and access.
public class Globals extends Application {
private static Globals instance;
private List<Float> current = new ArrayList<>();
@Override
public void onCreate() {
instance = this;
super.onCreate();
}
public float getCurrent() {
return current.get(current.size()-1);
}
public void setCurrent(float someVariable) {
this.current.add(someVariable);
}
public static Globals getInstance() {
return instance;
}
public static Context getContext(){
return instance;
// or return instance.getApplicationContext();
}
}
Now anywhere in app you can access the current variable or change the value by
Globals.getInstance().getCurrent();
Android Studio - Kotlin - Global Variables and Functions
Kotlin is much simpler. Don't create a class but an object:
object GlobalStuff {
var mainNavState: Int = 0
}
And use it like this from another class:
GlobalStuff.mainNavState = 1
val x = GlobalStuff.mainNavState
Kotlin Global Variable Showing As Zero 0
Don't worry, Kotlin is not doing anything weird or magical behind your back in this case.
The var
keyword in Kotlin means that you are declaring a variable, but the scope of that variable is not "global". The scope is the code block in which the variable is declared. In your case, you declared 3 variables in a class scope, so these are class variables and they can be accessed from anywhere inside the class MainActivity
. Since they are also public
(by default in Kotlin declarations are public, unless you specify a different access modifier, such as private
, protected
etc.), these 3 variables can also be accessed from outside the class (or from a subclass), as long as the calling code has a reference to an instance of this class. This works the same in Java, if something is public same access rules apply.
Since these are variables (their value can change) it also means that any code that has access to them, can also change their values. So the "weird" behavior that you are experiencing is likely due to some other part of code setting firstName
and secondName
to "0"
before your nameRating()
function is called, and that is why firstName
and secondName
are equal and the if
condition evaluates to true
.
In Android Studio, you can right-click on one of your variables and select "Find Usages". Search results will show up, and there you will see parts in code where other code might be changing the values of your variables. Hopefully that will shed some light on this behavior that you are seeing.
Kotlin set value of global variable
When your app starts one and only one object of the class MyApplication() will be created, so you don't need:
var mApp = MyApplication()
You can access MyApplication()
and all its members from everywhere in your app.
Declare a companion
object in MyApplication()
and put globalVar
's declaration inside:
class MyApplication: Application() {
companion object {
var globalVar = 2
}
override fun onCreate() {
super.onCreate()
// initialization code here
}
}
So in your MainActivity
class or elsewhere you can use MyApplication.Companion.globalVar
to get or set its value.
Or you can import the globalVar
variable in any class like:
import yourpackagename.MyApplication.Companion.globalVar
and refer to it simply globalVar
You also need to declare MyApplication
in the manifest:
<application
android:name=".MyApplication"
What is the difference between Global Variable and SharedPreferences android
- Global variable actually it's a parameter of the object. Lifetime of Global variable associate with object. I don't know exactly you create global variable (Example inside Activity, Application or Singleton...) but when User kill app it will be clean.
- SharedPreferences actually it is xml file format, you can store key-value to it and it still alive until User Uninstall App or Clear Data App in Setting.
Basically, if Global variable using when you only want it alive in object declare it. In case you want to keep data even app kill you should using Database or SharedPreferences, SharedPreferences good with simple data type or some settings of you app
I am trying to set a Global Variable Class, but it is crashing. Anything I am missing?
I am using this way
- Declare variable as public static
- call it anywhere by using name of class
for example
public class Main12 extends AppCompatActivity {
public static int age;
}
call it by
Main12.age = 4;
you can even call it in other activities same app
Related Topics
How to Make an Android Spinner With Initial Text "Select One"
How to Change the Status Bar Color in Android
Open Another Application from Your Own (Intent)
How to Disable Orientation Change on Android
How to Use Drawerlayout to Display Over the Actionbar/Toolbar and Under the Status Bar
Start_Sticky and Start_Not_Sticky
How to Load Script from Assets Index.Android.Bundle on Windows
Illegalstateexception: Can Not Perform This Action After Onsaveinstancestate With Viewpager
How to Display Count of Notifications in App Launcher Icon
How to Start New Activity on Button Click
Retrieve a Fragment from a Viewpager
How to Change Fontfamily of Textview in Android
Java Finished With Non-Zero Exit Value 2 - Android Gradle