Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android: how to use getApplication and getApplicationContext from non activity / service class

Tags:

android

I'm using extending application class on Android to share my data across the entire app.

I can use getApplication() method from all my activities.

However, there are certain custom helper classes I created; for example, an XMLHelper class which does not inherit from any activity / service class.

Here the getApplication() method is not available.

How do I sort this out and what are the best design practices to solve this?

like image 381
Raj Avatar asked Mar 17 '11 13:03

Raj


4 Answers

The getApplication() method is located in the Activity class, that's why you can't access it from your helper class.

If you really need to access your application context from your helper, you should hold a reference to the activity's context and pass it on invocation to the helper.

like image 117
mgv Avatar answered Nov 15 '22 14:11

mgv


The getApplication() method is located in the Activity class, so whenever you want getApplication() in a non activity class you have to pass an Activity instance to the constructor of that non activity class.

assume that test is my non activity class:

Test test = new Test(this);

In that class i have created one constructor:

 public Class Test
 {
    public Activity activity;
    public Test (Activity act)
    {
         this.activity = act;
         // Now here you can get getApplication()
    }
 }
like image 25
Chirag Avatar answered Nov 15 '22 12:11

Chirag


Casting a Context object to an Activity object compiles fine.

Try this:

((Activity) mContext).getApplication(...)

like image 22
Some Noob Student Avatar answered Nov 15 '22 13:11

Some Noob Student


Either pass in a Context (so you can access resources), or make the helper methods static.

like image 4
Robby Pond Avatar answered Nov 15 '22 13:11

Robby Pond