


You can get the parent activity from a Fragment by calling getActivity(). When you call getContext() from an Fragment, you will get the context of the activity in which that fragment is hosted in. ( ContextWrapper is a wrapper class, using which you can override any method of Context, while still retaining the original context) Get Context from Fragment : getContext() You can get the original context which was wrapped by ContextWrapper by calling contextWrapper.getBaseContext() This method is only useful when you are using ContextWrapper. You can directly access application context by calling getApplicationContext() or by calling on activity context like context.getApplicationContext() Get Original context : getBaseContext() So unlike activity context, which will be destroyed when close an activity, Application Context the application wide context which won’t get destroyed until you completely close application. If you need to access resources which are out of scope of specific activity, like when accessing SharedPreferences, displaying Toast message etc. Get App-level context : getApplicationContext() This will give the context of activity in which the view is currently hosted in. This method can be called on a View like textView.getContext(). If you are not directly inside Activity, for example inside an OnClickListener, you can get the current context by referencing with Activity name like MainActivity.this (Java) or (Kotlin) Get current activity context : View.getContext()

And as Activity is subclass of “Context”, you will get context of that activity. So, when use “this” keyword inside an Activity, it refers to that Activity instance. The this keyword in general sense refers to current class instance. So, it is important to know different types of Context and methods you can call to get context. It contains information about what Views are there, How they are laid out etc. Be is displaying a toast or Accessing database, you use context a lot while building Android app.Ĭontext is property, well, which can give you the context of whats happening on the Screen/Activity it belongs to. You need Context to perform a lot of things on Android. Context is one of the important and most used property.
