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

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?

This question is related to android

The answer is


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()
    }
 }

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>

Casting a Context object to an Activity object compiles fine.

Try this:

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


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


try this, calling the activity in the constructor

public class WebService {
private Activity activity;

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

        }
}

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