This is not a question about Context object itself. I wonder what the best way to manage reference to it. When I create android objects like Activity, Service, etc – context already accessible everywhere.
But I have bunch of different classes for data access, various shared utilities, etc. I find myself writing every call and passing context alone. I wonder if there any good way to deal with context. Maybe static? Is that good idea to store reference in my own Application object like so?
public class MyApplication extends Application
{
public static Context Context;
This way I can access context from anywhere in application. Does it seem like a good idea?
Make
public static Context mContext;as a global variable, and at the start ofonCreate(), addmContext = this;. It makes access much easier. By making it public and static, other files can see the context of your main activity, and you won’t have to pass it as a parameter to any function. In my opinion, this is probably the best/easiest way to manage reference to it. It also unclutters all sorts of references toMainActivity.this.alextsc’s comment shows a helpful link to problems that can occur from this as well.