I am so, so new to (a) Android, (b) Java and Kotlin, (c) classes, and so much more. Yet, I trying to get a basic app going (which it is) on my tablet, and I want to have the equivalent of a global variable to use / share between the various activities. And because I know so little, any of the solutions I find are missing some basic info that I need. So if anyone can help me that would be really nice :)
So, let's say I have two activities, and I want one global variable, e.g. mainNavState
So what I did was the following: In Android Studio, in the project folder, I right-clicked where the activities are, and selected New -> Kotlin Class File. I called in GlobalStuff. Not very inspired, I know. The contents of this new file are:
package com.example.myProj
public class GlobalStuff {
var mainNavState: Int = 0
public fun get_mainNavState(): Int {
return mainNavState
}
public fun set_mainNavState(newState: Int) {
mainNavState = newState
}
}
And now I try and use these functions from my activities.
So, in one activity, I do the following:
import com.example.myProj.GlobalStuff as glob
And then to call the functions:
navState = glob().get_mainNavState()
although I can't call the 'set' function:
glob().set_mainNavState(1)
it expects a member declaration.
So this is all basic stuff that I am trying to get a grasp on. AT some stage I can sit down and go through a course on Kotlin methodically etc., but for now I just want to get something basic going.
Things I might be doing wrong:
Perhaps I have created the wrong file TYPE for my global functions? It is a Kotlin Class file. Perhaps I need to instantiate it somewhere? Since I am defining a class, but not an actual instance of it?
Thanks for any help :)
Garrett
CodePudding user response:
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