Best practice to pass Context to non-activity classes?

AndroidAndroid ActivityAndroid Context

Android Problem Overview


So, my first major application is almost coded and I'm doing optimizations on my code. The app works fine, but I'm not sure about my way of passing the context to other classes. I don't want to do it the wrong way. I stumbled upon articles and questions here in Stackoverflow about contexts and which is the right way to pass it to non-activity classes. I read the documentation as well, but being a Finn makes complicated tech speak even harder to understand.

So, a simple question. Is my way of passing my main activity's context to other (helper) classes correct? If not, where can I read more about better practice on these situations.

For example: MainActivity.java

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle sis){
        super(sis);
        new Helper(MyActivity.this).makeMyAppAwesome();
    }
}

Helper.java

public class Helper {
    Context context;
    Helper(Context ctx){
        this.context = ctx;
    }

    public void makeMyAppAwesome(){
        makeBaconAndEggsWithMeltedCheese(context);
    }
}

Is this OK? It would be nice if someone could provide an easy to read article with examples on this subject.

Android Solutions


Solution 1 - Android

You can do that using ContextWrapper, as described here.

For example:

public class MyContextWrapper extends ContextWrapper {

    public MyContextWrapper(Context base) {
      super(base);
   }

    public void makeMyAppAwesome(){
        makeBaconAndEggsWithMeltedCheese(this);
    }
}

And call the non activity class like this from an Activity

new MyContextWrapper(this);

Solution 2 - Android

It is usually in your best interest to just pass the current context at the moment it is needed. Storing it in a member variable will likely lead to leaked memory, and start causing issues as you build out more Activities and Services in your app.

public void iNeedContext(Context context) {...

Also, in any class that has context, I'd recommend making a member variable for readability and searchability, rather than directly passing or (ClassName.)this. For example in MainActivity.java:

Context mContext = MainActivity.this;
Activity mActivity = MainActivity.this;

Solution 3 - Android

I have passed context like this which solved my problem:

    public class Utils extends ContextWrapper {
private final Context context;
    
    public Utils(Context context) {
        super(context);
        this.context = context;
    }
public void mymethod(){}
}

super(context); with ContextWrapper helped to make getBaseContext() and getApplicationContext() valid and this.context = context; captured context in variable which I can use wherever needed in methods. Maybe alternatively you can just opt for using a constructor with this.context = context; and replace all occurrences of getApplicationContext() and getBaseContext(). Well, an even better way is to pass context directly to the method if using only few from a class for avoiding memory leaks.

Solution 4 - Android

You could also create a static instance reference to your MainActivity initialized in the onCreate() method

public class MainActivity extends AppCompatActivity {

    public static MainActivity mMainActivity;

    @Override
    private onCreate(Bundle savedInstanceState){

    //...

    mMainActivity = this;

    }
}

and call the context like this:

MainActivity.mMainActivity;

or write a method getInstanceOf() if it's clearer and/or you prefer using an accessor

MainActivity.getInstanceOf();

This strategy might provide you with some flexibility if you decide later that you would like to call an instance method contained in your main activity like so:

MainActivity.mMainActivity.myInstanceMethod();

Just a suggestion. Criticism is welcome and encouraged.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIiro KrankkaView Question on Stackoverflow
Solution 1 - AndroidET-CSView Answer on Stackoverflow
Solution 2 - AndroidGiboltView Answer on Stackoverflow
Solution 3 - AndroidDh. YaduvanshiView Answer on Stackoverflow
Solution 4 - Androidthe_proleView Answer on Stackoverflow