2

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
katit
  • 17,375
  • 35
  • 128
  • 256
  • 1
    You can do that to a certain degree, if you want to store the application context. See [this question](http://stackoverflow.com/questions/987072/using-application-context-everywhere), which discusses the potential problems with this approach. What you should **never** do is store an Activity context in your application object. You will leak that context and get into problems. –  Jun 01 '12 at 17:06

1 Answers1

-1

Make public static Context mContext; as a global variable, and at the start of onCreate(), add mContext = 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 to MainActivity.this.

alextsc's comment shows a helpful link to problems that can occur from this as well.

Mxyk
  • 10,678
  • 16
  • 57
  • 76
  • or should create static getter. – Simon Dorociak Jun 01 '12 at 17:26
  • I already subclass Application anyway. My app uses services, receivers, etc. Activity is just part of app. I think it would be better to expose MyApplication as static - seems like this context (Application itself) works good everywhere I needed context. – katit Jun 01 '12 at 17:52
  • 1
    That's a memory leak: https://stackoverflow.com/questions/11908039/android-static-fields-and-memory-leaks – m0skit0 May 12 '18 at 23:39