Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in context this and getContext()

What is difference between this and getContext(), when I say this I mean this within an Activity.

like image 700
Lukap Avatar asked Jun 03 '11 15:06

Lukap


People also ask

What is the difference between getContext () getApplicationContext () getBaseContext () and this?

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.

What is the difference between getActivity and getContext?

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 .

What is the difference between this context and getApplicationContext which one to use when?

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.

What is the difference between context and requireContext?

getContext() returns a nullable Context . requireContext() returns a nonnull Context , or throws an exception when one isn't available.


2 Answers

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).

  1. If class extends ContextWrapper then you can use this as Context. Such classes normally do not have getContext() method.

  2. 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.

like image 171
inazaruk Avatar answered Oct 11 '22 09:10

inazaruk


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).

like image 41
Ted Hopp Avatar answered Oct 11 '22 09:10

Ted Hopp