I'm developing an Android app with Kotlin.
For example I have an access token which I get on my LoginActivity and I need this access token on each activity to call API. I know that I could use putExtra() and getExtra(), but it doesn't make sense to write this code for each new activity.
Is there a way to create a global variable or something like static class which will be accessible for all activities in app?
What is the right Android approach for that?
CodePudding user response:
I think an object
or companion object
is what you are looking for.
Be warned is is possible for an instance of an object
to be garbage collected without your control. I would recommend creating a BaseActivity class that all your Activities inherit from and override the following methods.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
savedInstanceState?.let {
MyObject.refreshFromBundle(it)
}
}
override fun onSaveInstanceState(outState: Bundle) {
MyObject.populateBundle(outState)
super.onSaveInstanceState(outState)
}
Then in your object
have the following functions
fun refreshFromBundle(bundle: Bundle) {
// Get info from bundle and populate your variables
}
fun populateBundle(bundle: Bundle) {
// Put info from variables into the bundle
}
More info on why it is necessary here
CodePudding user response:
You can use a simple class.
public class Important{
private static String key = "";
public static void setKey(String key){
this.key = key;
}
public static String getKey(){
return key;
}
}
Create this class under in your package. When you get your key just call Important.setKey("key")
. Then you can get your key anytime anywhere by calling Important.getKey()