For example, I use 3 activities: SplashActivity, LoginActivity, MainActivity. In each of them I use elements in which contexts are required (Toast, methods of external classes, methods of current Activity, etc.).

Suppose, if you use Toast inside the application, then everything is as follows:

Toast.makeText(this, "Current activity toast", Toast.SHORT).show(); 

But what if, say, it is necessary to use Toasts out of activity? Suppose in any external class.
The first thing that people notice is that they usually pass in the Context method parameter and do a context check on the null in the method itself. But, as it seems to me, this method does not solve the whole question.
And the second is the invocation of the application context ( getApplicationContext () ) in the outer class.

Therefore, such a question arose ... Is it best to be attached to each individual context (a single Activity) or to create one global context and use it throughout the application? Here, a person says that it is best to make a singleton and take it like this:

 Application.getApplicationContext(); 

Can you share your experience using contexts in your projects with minimal risk of getting NPE? I will be glad to your wishes.

PS Yes, you can use Dagger 2 and enjoy life, but it is precisely the decision of the issue "head on."

    1 answer 1

    I consider implementation with sigltonom in the form of applicationContext quite acceptable. The most real problem associated with this approach is the unit testing problem. I know some developers highlight the problems associated with violation of encapsulation and violation of the law of Demeter, I think in the context of this task to talk about such things does not make sense.

    Use applicationContext everywhere is not worth it (after all, there is a difference between contexts). Within representations that are specific to a particular activit, it is quite possible to use an activit context. And your example with Toast output outside of activation is a rather strange task. It is better to return information (for example, an error) to activation and display your Toast there than to interact with ui, don’t understand where it comes from.

    • it would be nice to add that indiscriminate use of contexts at different levels is the first cause of memory leaks - pavlofff
    • Okay, with the toast in the outer class, it was soaking up. Suppose now I have a class not related to Activity (NetworkHelper). It has one single method, the static isConnected method, in which the network connection is checked. This method is used often and everywhere and it needs context. I understand, here you need to use getApplicationContext from the singleton class? And again, I am haunted by the mania that is more beautiful in the form of NPE, although I know that ApplicationContext lives throughout the entire life cycle of an application, and not Activity .... - Tomas