506

In an Android app, is there anything wrong with the following approach:

public class MyApp extends android.app.Application {

    private static MyApp instance;

    public MyApp() {
        instance = this;
    }

    public static Context getContext() {
        return instance;
    }

}

and pass it everywhere (e.g. SQLiteOpenHelper) where context is required (and not leaking of course)?

10
  • 23
    Just to elaborate for others implementing this, you can then modify the <application> node of your AndroidManifest.xml file to include the following attribute definition: android:name="MyApp". MyApp needs to be under the same package that your manifest references. Commented Sep 20, 2010 at 3:50
  • Why the static? The application instance is always created before anything else. Wherever you are expected to access the application context, it will be passed to you as arguments. This approach may complicate your tests. Static-itis promotes common coupling. Commented Oct 14, 2010 at 22:41
  • 8
    Just so you know you're returning your application by one of its super interfaces, so if you provided additional methods within MyApp you would not be able to use them. Your getContext() should instead have a return type of MyApp, and that way you can use methods added later, as well as all the methods in ContextWrapper and Context. Commented Aug 9, 2011 at 1:28
  • 5
    See also stackoverflow.com/questions/2002288/… - it's another reply related to similar post. Better set the static variable in onCreate and not c'tor. Commented Oct 31, 2011 at 15:44
  • 1
    @ChuongPham If the framework has killed your app, there won't be anything accessing the null context... Commented Apr 24, 2015 at 23:14

10 Answers 10

435

There are a couple of potential problems with this approach, though in a lot of circumstances (such as your example) it will work well.

In particular you should be careful when dealing with anything that deals with the GUI that requires a Context. For example, if you pass the application Context into the LayoutInflater you will get an Exception. Generally speaking, your approach is excellent: it's good practice to use an Activity's Context within that Activity, and the Application Context when passing a context beyond the scope of an Activity to avoid memory leaks.

Also, as an alternative to your pattern you can use the shortcut of calling getApplicationContext() on a Context object (such as an Activity) to get the Application Context.

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for an inspiring answer. I think I'll use this approach solely for the persistence layer (as I don't want to go with content providers). Wondering what was the motivation behind designing SQLiteOpenHelper in a way that expects a Context to be supplied instead of acquiring it from Application itself. P.S. And your book is great!
Using the application context with LayoutInflator just worked for me. Must have been changed in the last three years.
@JacobPhillips Using LayoutInflator without an activity context will miss out on that Activity's styling. So it would work in one sense, but not another.
@MarkCarter Do you mean using the Application Context will miss out on the Activity's styling?
@JacobPhillips yes, the Application Context cannot have the styling because every Activity may be styled in a different way.
|
31

In my experience this approach shouldn't be necessary. If you need the context for anything you can usually get it via a call to View.getContext() and using the Context obtained there you can call Context.getApplicationContext() to get the Application context. If you are trying to get the Application context this from an Activity you can always call Activity.getApplication() which should be able to be passed as the Context needed for a call to SQLiteOpenHelper().

Overall there doesn't seem to be a problem with your approach for this situation, but when dealing with Context just make sure you are not leaking memory anywhere as described on the official Google Android Developers blog.

Comments

14

Some people have asked: how can the singleton return a null pointer? I'm answering that question. (I cannot answer in a comment because I need to post code.)

It may return null in between two events: (1) the class is loaded, and (2) the object of this class is created. Here's an example:

class X {
    static X xinstance;
    static Y yinstance = Y.yinstance;
    X() {xinstance=this;}
}
class Y {
    static X xinstance = X.xinstance;
    static Y yinstance;
    Y() {yinstance=this;}
}

public class A {
    public static void main(String[] p) {
    X x = new X();
    Y y = new Y();
    System.out.println("x:"+X.xinstance+" y:"+Y.yinstance);
    System.out.println("x:"+Y.xinstance+" y:"+X.yinstance);
    }
}

Let's run the code:

$ javac A.java 
$ java A
x:X@a63599 y:Y@9036e
x:null y:null

The second line shows that Y.xinstance and X.yinstance are null; they are null because the variables X.xinstance ans Y.yinstance were read when they were null.

Can this be fixed? Yes,

class X {
    static Y y = Y.getInstance();
    static X theinstance;
    static X getInstance() {if(theinstance==null) {theinstance = new X();} return theinstance;}
}
class Y {
    static X x = X.getInstance();
    static Y theinstance;
    static Y getInstance() {if(theinstance==null) {theinstance = new Y();} return theinstance;}
}

public class A {
    public static void main(String[] p) {
    System.out.println("x:"+X.getInstance()+" y:"+Y.getInstance());
    System.out.println("x:"+Y.x+" y:"+X.y);
    }
}

and this code shows no anomaly:

$ javac A.java 
$ java A
x:X@1c059f6 y:Y@152506e
x:X@1c059f6 y:Y@152506e

BUT this is not an option for the Android Application object: the programmer does not control the time when it is created.

Once again: the difference between the first example and the second one is that the second example creates an instance if the static pointer is null. But a programmer cannot create the Android application object before the system decides to do it.

UPDATE

One more puzzling example where initialized static fields happen to be null.

Main.java:

enum MyEnum {
    FIRST,SECOND;
    private static String prefix="<", suffix=">";
    String myName;
    MyEnum() {
        myName = makeMyName();
    }
    String makeMyName() {
        return prefix + name() + suffix;
    }
    String getMyName() {
        return myName;
    }
}
public class Main {
    public static void main(String args[]) {
        System.out.println("first: "+MyEnum.FIRST+" second: "+MyEnum.SECOND);
        System.out.println("first: "+MyEnum.FIRST.makeMyName()+" second: "+MyEnum.SECOND.makeMyName());
        System.out.println("first: "+MyEnum.FIRST.getMyName()+" second: "+MyEnum.SECOND.getMyName());
    }
}

And you get:

$ javac Main.java
$ java Main
first: FIRST second: SECOND
first: <FIRST> second: <SECOND>
first: nullFIRSTnull second: nullSECONDnull

Note that you cannot move the static variable declaration one line upper, the code will not compile.

1 Comment

Useful example; its good to know that there is such a hole. What I take away from this is that one should avoid referring to such a static variable during static initialization of any class.
11

Application Class:

import android.app.Application;
import android.content.Context;

public class MyApplication extends Application {

    private static Context mContext;

    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();
    }

    public static Context getAppContext() {
        return mContext;
    }

}

Declare the Application in the AndroidManifest:

<application android:name=".MyApplication"
    ...
/>

Usage:

MyApplication.getAppContext()

3 Comments

Prone to memory leaks. You shouldn't ever do this.
@Dragas, no it is not prone to leaks. You can do that any time.
@Dragas getApplicationContext() is actually previously leaked, so using this example won't be a problem.
9

You are trying to create a wrapper to get Application Context and there is a possibility that it might return "null" pointer.

As per my understanding, I guess its better approach to call- any of the 2 Context.getApplicationContext() or Activity.getApplication().

4 Comments

when should it return null?
There's no static Context.getApplicationContext() method that I'm aware of. Am I missing something?
I also implement the same approach in my application, but when calling in SQLiteOpenHelper, it returns the null pointer. Any answer for this kind of situation.
This may be the case if you call SQLiteOpenHelper in a contentprovider which is loaded before the app.
5

It is a good approach. I use it myself as well. I would only suggest to override onCreate to set the singleton instead of using a constructor.

And since you mentioned SQLiteOpenHelper: In onCreate () you can open the database as well.

Personally I think the documentation got it wrong in saying that There is normally no need to subclass Application. I think the opposite is true: You should always subclass Application.

Comments

3

I would use Application Context to get a System Service in the constructor. This eases testing & benefits from composition

public class MyActivity extends Activity {

    private final NotificationManager notificationManager;

    public MyActivity() {
       this(MyApp.getContext().getSystemService(NOTIFICATION_SERVICE));
    }

    public MyActivity(NotificationManager notificationManager) {
       this.notificationManager = notificationManager;
    }

    // onCreate etc

}

Test class would then use the overloaded constructor.

Android would use the default constructor.

Comments

1

I like it, but I would suggest a singleton instead:

package com.mobidrone;

import android.app.Application;
import android.content.Context;

public class ApplicationContext extends Application
{
    private static ApplicationContext instance = null;

    private ApplicationContext()
    {
        instance = this;
    }

    public static Context getInstance()
    {
        if (null == instance)
        {
            instance = new ApplicationContext();
        }

        return instance;
    }
}

7 Comments

Extending android.app.application already guarantees singleton so this is unnecessary
What if you want acess from non activity classes?
You should never new the Application yourself (with the possible exception of unit testing). The operating system will do that. You should also not have an constructor. That is what onCreate is for.
@Vincent: can you post some link on this ? preferably code - I am asking here : stackoverflow.com/questions/19365797/…
@radzio why we shouldn't do it in constructor?
|
0

I'm using the same approach, I suggest to write the singleton a little better:

public static MyApp getInstance() {

    if (instance == null) {
        synchronized (MyApp.class) {
            if (instance == null) {
                instance = new MyApp ();
            }
        }
    }

    return instance;
}

but I'm not using everywhere, I use getContext() and getApplicationContext() where I can do it!

4 Comments

So, please write a comment to explain why you've downvoted the answer so I can understand. The singleton approach is widely used to get a valid context outside activities or views body...
No need as the operating system ensures that the Application is instantiated exactly once. If any I would suggest to set the Singelton in onCreate ().
A good thread-safe way to lazy initialize a singleton, but not neccessary here.
Wow, just when I thought people had finally stopped using double-checked locking... cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
0

I know the original question was posted 13 years ago, and this is the Kotlin version of getting context everywhere.

class MyApplication : Application() {
    companion object {
        @JvmStatic
        private var instance: MyApplication? = null

        @JvmStatic
        public final fun getContext(): Context? {
            return instance
        }
    }

    override fun onCreate() {
        instance = this
        super.onCreate()
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.