We are trying to set the value of a global variable declared in the code below
class MyApplication: Application() {
var globalVar = 2
}
Now we have a Main Activity that has a Edit Text named etPerson we would like to enter a value in etPerson and set the entered value equal to globalVar
Why because we want to make a call to a database function in another Activity
Here is the code that makes the call to the DB
var mApp = MyApplication()
var intGlobalVar = mApp.globalVar
println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@ globalINT = "+intGlobalVar)
var ITEM = db.getItem(intGlobalVar)
println("%%%%%%%%%%%%%%%%%% ITEM "+ITEM?.id+" name "+ITEM?.name)
And for clarity here is the DB function
fun getItem(id: Int): Contact? {
val db = this.writableDatabase
val selectQuery = "SELECT * FROM $TABLE_NAME WHERE $colId = ?"
db.rawQuery(selectQuery, arrayOf(id.toString())).use {
// .use requires API 16
if (it.moveToFirst()) {
val result = Contact(0)
result.id = it.getInt(it.getColumnIndex(colId))
result.name = it.getString(it.getColumnIndex(colName))
return result
}
}
return null
}
So the issue is setting the var globalVar to the value entered in etPerson on the Main Activity
The concept can be accomplished using put and get with intents but that is not our goal here
Our question is how to set the globalVar to the value entered in the Edit Text?
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"