Home > Software design >  Android create global variable which holds its state
Android create global variable which holds its state

Time:09-16

I have an application in that whenever the internet connectivity changes , I need to make some variables in another activities unclickable. Since internet connectivity might change in the first activity , hence the 2nd activity wont have any idea if the internet connectivity is there or not .

I need a way to create a global variable or a class which holds this status , So that all the activity can get the variable value and handle responses accordingly .

My initial idea was to create a base activity and make another activities inherit it. But since that is a bad use of inheritence , I am searching for some other solutions.

Is there anything like that build in inside android or kotlin , Except for sharedPreferences ?

CodePudding user response:

I think you can use the singleton pattern. In Kotlin it's super easy:

object InternetConnectivityState {
  val connected: Boolean = false
}

And then you just update and read from the singleton object and it will be shared globally within your app process. For example:

myButton.enabled = InternetConnectivityState.connected

CodePudding user response:

You can store global variables

  • in specially declared object singletons, just like Maurice mentioned
  • in companion object
  • in variables declared ouside of any class.

Of course, it's your choice if it's good practice. Dogma that 'singleton is bad' is not useful without understanding, why is it ))

  • Related