I am creating a custom class in main application class. Lets say My mainAccount
.
Now, i am creating many activities. I want to mainAccount
variable in every activity, how can i do that? One way is to put in intent and pass to each activity. Is there any better way, like making it global etC?
Best Regards
Look up Singleton classes. Basically, you want something like this.
public class Singleton {
private static Singleton instance = null;
protected Singleton() {
// Exists only to defeat instantiation.
}
public static Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
Then, for any class that needs access to the class, call:
Singleton var=Singleton.getInstance();
This is essentially global, without most of the negative consequences of global variables. It will ensure that only one object of that class can exist, but everyone who needs it can access it.
You can use "singleton" class, or "static" class (if you don't need to initialize it, instantiate or inherit or implement interfaces).
Singleton class:
public class MySingletonClass {
private static MySingletonClass instance;
public static MySingletonClass getInstance() {
if (instance == null)
instance = new MySingletonClass();
return instance;
}
private MySingletonClass() {
}
private String val;
public String getValue() {
return val;
}
public void setValue(String value) {
this.val = value;
}
}
String s = MySingletonClass.getInstance().getValue();
Static class:
public class MyStaticClass {
public static String value;
}
String s = MyStaticClass.value;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With