Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Access Android Custom Application Object in simple Java Class which Also has ApplicationContext object?

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.

like image 734
Shridutt Kothari Avatar asked Feb 08 '13 15:02

Shridutt Kothari


2 Answers

You can get the Application class with getApplicationContext from Context with the good casting

((A) this.ctx.getApplicationContext()).abc;
like image 74
Plumillon Forge Avatar answered Oct 18 '22 09:10

Plumillon Forge


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;
like image 36
David Wasser Avatar answered Oct 18 '22 10:10

David Wasser