TLDR issue: How can I access a global variable (that gets updated) from my main class in my composable functions? I have reviewed other SO posts (e.g., 1, 2) and created the companion object as a result, but nothing works.
The details:
I have onCreate()
and a userEmailAddressString
variable in my MainActivity
class. onCreate()
first calls restoreState()
to authorize a user into my app.
Later on, I have a Composable function that creates a Card (in the code below, I call MainView()
which has a reference to HeaderCard()
), where I want to display the user’s email address on the screen.
My issue is (probably) around scopes. I cannot obtain the correct value in the companion object, while the correct value is displayed in my onCreate()
. The logs below show that the getEmailAddy()
in my companion object returns the default value of NOT LOGGED IN
instead of my email address. Thoughts on how to fix this?
Here’s what I see in my logs:
GCTAG com.x D on create
GCTAG com.x D on create log, email string: Logged in as <myemail>@gmail.com
GCTAG com.x D in getEmailAddy, email string: NOT LOGGED IN
class MainActivity : ComponentActivity() {
// My variable that i want to use globally
var userEmailAddressString : String = "NOT LOGGED IN"
// onCreate
override fun onCreate(savedInstanceState: Bundle?) {
// call restore state to auth the user first
restoreState()
Log.d(LOG_TAG, "on create")
val userEmailAddress = jwt?.getClaim("email")?.asString().toString()
if (userEmailAddress != "null") {
userEmailAddressString = "Logged in as $userEmailAddress"
}
Log.d(LOG_TAG, "on create log, email string: $userEmailAddressString")
setContent {
XJetpackTheme {
Surface (
modifier = Modifier.fillMaxSize()
) {
MainView()
}
}
}
}
companion object {
fun getEmailAddy(mainActivity: MainActivity): String {
Log.d(mainActivity.LOG_TAG, "in getEmailAddy, email string: " + mainActivity.userEmailAddressString)
return mainActivity.userEmailAddressString
}
}
}
@Composable
fun HeaderCard() {
OutlinedCard(
// my formatting that i removed for brevity
) {
Text(
text = MainActivity.getEmailAddy(MainActivity()),
// modifier, align, and style that i removed for brevity
)
}
}