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."