0

For example, I am doing the following and then later referencing the applicationContext from within all of my inner classes.

public class MobileApplication extends Application {

    public static Context appContext;

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

Future class,

public class RandomClass {
    public void doSomething() {
       MobileApplication.appContext.toString();
    }
}

I am not sure of the drawbacks of doing something like this VS passing in my context every single time i need one.

Kamilski81
  • 14,409
  • 33
  • 108
  • 161
  • 1
    The context may be null some times so your calling code needs to handle it appropriately. See comments from the answer here http://stackoverflow.com/questions/2002288/static-way-to-get-context-on-android?rq=1 – Naveed Mar 03 '16 at 22:13
  • 2
    Application is a singleton (one application object per process). This is perfectly valid. Don't use it for inflating views. – Eugen Pechanec Mar 03 '16 at 22:14

1 Answers1

1

Here's what I got off the top of my head

  1. It makes it difficult to unit test. There's a tight coupling between the client and this Application class. I've had times where I need to test with a custom application class or a custom context.
  2. (Check me on this), but context won't get recreated on rotation. You're stuck with that context whenever it was created. I don't think it would play well if you're supporting different dimens or locales.
  3. Possibility it could be null.
  4. Certain new UI widgets want the getSupportActionBar().getThemedContext() context. This approach doesn't encourage that usage.
  5. The link Naveed gave you is quite nice as well.

In general, I just find it very easy to pass or get a context where needed.

Community
  • 1
  • 1
whizzle
  • 2,053
  • 17
  • 21