55

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?

Michael Currie
  • 13,721
  • 9
  • 42
  • 58
Raj
  • 6,810
  • 6
  • 48
  • 56

8 Answers8

60

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.

Erfan
  • 163
  • 11
mgv
  • 8,384
  • 3
  • 43
  • 47
  • 1
    i have got tons of different xml feeds to parse and either update global variables OR insert into sqlite based on different scenarios... so instead of creating a new xml parser class i thought for simplicity purpose the best and simplest way is to create a single xml parser class which takes care of all the xml parsing logic for all scenarios. i have global variables shared via application class and for sqlite i have a singleton data helper class (also exposed via application class) and hence the need for getApplication() or getApplicationContext() in helper classes – Raj Mar 17 '11 at 14:05
  • Then just pass your activity's context to the helpers. Note that by sharing everything in multiple places you are creating a tightly coupled design. – mgv Mar 17 '11 at 14:24
  • 3
    this is wrong for leaking activity context outside of activity lifecycle.. you should use something like WeakReference to the context you are sending to any helper objects outside of your activity – aimiliano Mar 06 '16 at 13:30
27

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()
    }
 }
Chirag
  • 56,621
  • 29
  • 151
  • 198
  • Your way is good. It's very useful but what to do in the case when we call a service class through intent? LIKE Intent myIntent = new Intent(context, AutoSyncService.class); "AutoSyncService" is my service class than how to use context in that class? – Yog Guru May 14 '12 at 05:31
  • Try this https://www.dev2qa.com/android-get-application-context-from-anywhere-example/ – Moses Ndeda Apr 21 '19 at 21:46
22

Casting a Context object to an Activity object compiles fine.

Try this:

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

Erfan
  • 163
  • 11
Some Noob Student
  • 14,186
  • 13
  • 65
  • 103
4

In order to avoid to pass this argument i use class derived from Application

public class MyApplication extends Application {

private static Context sContext;

@Override
public void onCreate() {
    super.onCreate();
    sContext=   getApplicationContext();

}

public static Context getContext() {
    return sContext;
}

and invoke MyApplication.getContext() in Helper classes.

Don't forget to update the manifest.

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
package="com.example"> 
      <application 
       android:name=".MyApplication"
       android:allowBackup="true" 
       android:icon="@mipmap/ic_launcher" 
       android:label="@string/app_name"> 
         <activity....>
            ......
         </activity>
     </application> 
</manifest>
sandSK
  • 3
  • 4
Lapenkov Vladimir
  • 3,066
  • 5
  • 26
  • 37
4

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

Robby Pond
  • 73,164
  • 16
  • 126
  • 119
2

Sending your activity context to other classes could cause memoryleaks because holding that context alive is the reason that the GC can't dispose the object

RClemens
  • 301
  • 2
  • 7
  • This should only be a problem if the instance you are passing the context to is itself static or is referred to by another static object. If you are using Android Studio the inspectors will be able to discover most such problems. – Kevin Whitefoot Dec 03 '16 at 12:38
0

try this, calling the activity in the constructor

public class WebService {
private Activity activity;

        public WebService(Activity _activity){
            activity=_activity;
            helper=new Helper(activity);

        }
}
kgandroid
  • 5,507
  • 5
  • 39
  • 69
Issac Balaji
  • 1,441
  • 1
  • 13
  • 25
0
((MyApplication) getApplicationContext()).myMethod()
Kelvin Schoofs
  • 8,323
  • 1
  • 12
  • 31
Lee
  • 13
  • 1
  • 3