0

I'm looking for ways to access application context in some classes that are used in background threads.

Besides that I'm avoiding to pass the context from my UI as a parameter to every single class.

With this in mind I'm doing something like this:

public class LojaApplication extends Application {

    private static Context applicationContext;

    @Override
    public void onCreate() {
        super.onCreate();

        applicationContext = this;
    }

    public static Context getMyContext() {
        return applicationContext;
    }
}

And then using it:

public class WorkerClass {
    private final Context applicationContext;

    public WorkerClass() {
        this.context = MyApplication.getMyContext();
    }

    public void doSomeStuffOnBackground(){
        ...
        String string = applicationContext.getString(...)
        ...
    }
}

I was worried that MyApplication.getMyContext() would return null if called inside a static block, but in my tests this works as well.

Is there a scenario that this might fail? Or problems that I'm failing to predict?

The point here is that I'm trying to avoid passing the context around as a parameter. I'm aware that is possible to access the Application Context via Context.getApplicationContext() that come from the Activity, but to do that I need to pass it as a parameter, what I'm trying to avoid.

PS.: I'm aware of the limitations of Application Context vs Activity Context.

Cedulio Cezar
  • 288
  • 3
  • 10
  • 1
    If your application is running in any way shape or form the application context will not be null. That being said, you should still be very careful passing around a static context. Not that it is the same with an application as it is an activity, but it can lead to bad practices. – zgc7009 Jun 15 '16 at 14:22
  • Why you don't use a `singleton` and store the `applicationContext` in it? – wake-0 Jun 15 '16 at 14:31
  • Why can't you just call `getApplicationContext()`? – SQLiteNoob Jun 15 '16 at 14:52
  • @SQLiteNoob is the method `getApplicationContext()` not inherited from the `Application`? So it is not possible to call it from somewhere else – wake-0 Jun 15 '16 at 15:21
  • @SQLiteNoob to do that I would need to pass Activity(Context) as parameter, which I'm trying to avoid. – Cedulio Cezar Jun 15 '16 at 15:53
  • @KevinWallis could you elaborate? I don't get it. – Cedulio Cezar Jun 15 '16 at 15:54
  • @CedulioCezar the method `getApplicationContext` is a method from the class `ContextWrapper` so only class which inherit from this class contain also this method. Or have you asked about the `singleton`? – wake-0 Jun 15 '16 at 16:05
  • @KevinWallis I mean singleton approach. – Cedulio Cezar Jun 16 '16 at 19:10
  • it would be possible to use a singleton approach instead of `static` – wake-0 Jun 16 '16 at 19:12

0 Answers0