What is difference between this
and getContext()
, when I say this
I mean this
within an Activity
.
getApplicationContext() - Returns the context for all activities running in application. getBaseContext() - If you want to access Context from another context within application you can access. getContext() - Returns the context view only current running activity.
getContext() - Returns the context view only current running activity. getActivity()- Return the Activity this fragment is currently associated with. getActivity() can be used in a Fragment for getting the parent Activity of the Fragment .
This generally should only be used if you need a Context whose lifecycle is separate from the current context, that is tied to the lifetime of the process rather than the current component. Actually in general it is better to use getApplicationContext() since it will less likey lead to memory leaks.
getContext() returns a nullable Context . requireContext() returns a nonnull Context , or throws an exception when one isn't available.
In general there are two type of classes. Ones that extend ContextWrapper
class (Activity
, Service
, Application
) and those that do not extend it (like View
).
If class extends ContextWrapper
then you can use this
as Context
. Such classes normally do not have getContext()
method.
Those classes that do not extend ContextWrapper
but still save and use Context
normally expose getContext()
function. And you cannot use this
as Context
in such cases.
And these two cases are mutually exclusive. At least I don't recall classes that extend ContextWrapper
and have getContext
at the same time.
getContext()
is not defined in an Activity. It's used in a View
(or View
subclass) to get a reference to the enclosing context (an Activity).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With