How can I get the current context of work in Android?

I am trying to get the current working context in android, I was trying 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 an error

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

+5
source share
2 answers

This works 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 just need to call MyApplication.getContext()any part of your application.

I assume the application XML tag is in manifest.xml

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

You do not need to create any instance of the Application class, it will be created when the application starts, before anything.

+14
source

Application, ,

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

getApplicationContext().

0

All Articles