Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get current running context in Android?

Tags:

android

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

like image 470
nkarmi Avatar asked Jun 25 '12 10:06

nkarmi


2 Answers

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.

like image 159
Goofyahead Avatar answered Nov 10 '22 23:11

Goofyahead


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.

like image 21
Lalit Poptani Avatar answered Nov 11 '22 00:11

Lalit Poptani