Static way to get ‘Context’ in Android?

Do this: In the Android Manifest file, declare the following. <application android:name=”com.xyz.MyApplication”> </application> Then write the class: public class MyApplication extends Application { private static Context context; public void onCreate() { super.onCreate(); MyApplication.context = getApplicationContext(); } public static Context getAppContext() { return MyApplication.context; } } Now everywhere call MyApplication.getAppContext() to get your application context statically.

When to call activity context OR application context?

getApplicationContext() is almost always wrong. Ms. Hackborn (among others) have been very explicit that you only use getApplicationContext() when you know why you are using getApplicationContext() and only when you need to use getApplicationContext(). To be blunt, “some programmers” use getApplicationContext() (or getBaseContext(), to a lesser extent) because their Java experience is limited. They implement … Read more

return object of getContext

Context is an interface to global information about an application environment. Activity class extends ContextThemeWrapper, if you want your activity as a parameter, you need to cast the context to your activity or create your Interface between your components. If you want to know why, you need to read the source code: https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/view/LayoutInflater.java At line … Read more