currently, in my App I have the following class:
public class MyApp extends Application {
private static Context context;
public void onCreate(){
super.onCreate();
MyApp.context = getApplicationContext();
}
public static Context getContext() {
return MyApp.context;
}
}
I use this to have Context in classes that are neither Activities nor Fragment. It's there any difference between use the context stored on this class and use and activity as context? It is a good practice to have this class or should I provide an activity as context to any class who needs it?
Thanks.
The solution itself is fairly simple: Do not place context fields in static instances, whether that of a wrapping class or declaring it static directly. And the solution to the warning is simple: don't place the field statically. In your case, pass the context as an instance to the method.
It is used to return the Context which is linked to the Application which holds all activities running inside it. When we call a method or a constructor, we often have to pass a Context and often we use “this” to pass the activity Context or “getApplicationContext” to pass the application Context.
Definition. it's the context of current state of the application/object. It lets newly-created objects understand what has been going on. Typically, you call it to get information regarding another part of your program (activity and package/application).
There are essentially two types of context : Application Context. Activity Context.
It's there any difference between use the context stored on this class and use and activity as context?
Yes. Please read Dave Smith's epic blog post on the subject. In summary: only use an Application
when you know why Application
is the right answer... and it rarely is.
It is a good practice to have this class
IMHO, not usually. You may sometimes need an Application
object, but you do not need your own custom subclass, and you do not need to make it a singleton.
should I provide an activity as context to any class who needs it?
You supply the right Context
instance to any method that needs it. As Dave Smith describes in that blog post, not all Context
instances are created equal. Only use Application
when Application
is the right sort of Context
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With