10

I am trying to get current running context in android, I tried to use:

<application android:name="com.xyz.MyApplication">

</application>

public class MyApplication extends Application
{
    private static Context context;

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

    public static Context getAppContext() 
    {
        return MyApplication.context;
    }
}

When I try to use MyApplication.getAppContext(), it gives me the error

AndroidRuntime(14421): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

2
  • You only set the context on the creation of the object, the static reference will return null if you haven't created the Application.
    – cjk
    Commented Jun 25, 2012 at 10:35
  • What do you mean by "they don't work correctly"? Some errormessage? Some unexpected behaviour that you could explain a little more? Then somebody can (and will) help you :)
    – basti
    Commented Jun 25, 2012 at 10:35

2 Answers 2

19

This is working for me:

public class MyApplication extends Application {

private static Context mContext;

@Override
public void onCreate() {
    super.onCreate();
    mContext = getApplicationContext();
}
public static Context getContext() {
    return mContext;
}
}

You will just need to call MyApplication.getContext() on any part of your app.

I'm assuming that the application XML tag is on the manifest.xml

<application
    android:name=".MyApplication"
    android:icon="@drawable/icon"
    android:label="@string/app_name" >

You don't need to create any instance of Application class, it will be created when you launch the app, before anything.

4
  • Thank you for reply, but still doesn't work they give me this error AndroidRuntime(14421): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
    – nkarmi
    Commented Jun 25, 2012 at 10:57
  • Can you post your manifest.xml and review the package name and app class name?
    – Goofyahead
    Commented Jun 25, 2012 at 11:54
  • but you made a memory leak with static Context ?!! Commented Apr 30, 2020 at 12:01
  • "Do not place Android context classes in static fields; this is a memory leak"
    – O-9
    Commented Feb 12, 2021 at 14:31
1

If you want to get the instance of Application class you can get it using,

MyApplication Obj = ((MyApplication )getApplicationContext());

If context then getApplicationContext() itself is enough.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.