I have created a custom application class like this:
class A extends android.app.Application{
public String abc = "xyz";
}
And I have a simple java class
class B {
private appContext;
// This constructor is called from activity.
B(Context ctx){
this.appContext = ctx;
}
private void foo(){
// want to access Class A's abc String vairable Here...HOW TO DO THAT?????
}
}
How to access Class A's abc String vairable in foo method.
You can get the Application class with getApplicationContext
from Context
with the good casting
((A) this.ctx.getApplicationContext()).abc;
The Application
class in Android is a singleton and therefore so is your derived class. Android will create just one instance of your class A
when it starts your application. Just change
class A extends android.app.Application {
public String abc = "xyz";
}
to
class A extends android.app.Application {
public static String abc = "xyz";
}
and you can reference it from anywhere like this:
String foo = A.abc;
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