34

I am very confused with the usage of all these that where should we use them.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Mr Singh
  • 415
  • 1
  • 6
  • 14

3 Answers3

46

this - return self reference
getContext() - return Context
getActivity() - return Activity

Context.

Quote from original answer :

As the name suggests, its the context of current state of the application/object. It lets newly created objects understand what has been going on. Typically you call it to get information regarding another part of your program (activity, package/application)

Activity

Activity is a Java code that supports a screen or UI. In other words, building block of the user interface is the activity. Activity class is a pre-defined class in Android and every application which has UI must inherit it to create window. Activity represents the presentation layer of an Android application, e.g. a screen which the user sees. An Android application can have several activities and it can be switched between them during runtime of the application.

Note : Activity extends Context. Context not an Activity.

Community
  • 1
  • 1
Sergey Shustikov
  • 15,377
  • 12
  • 67
  • 119
  • Please cite @Sameer Segal answer in regards to your answer for Context which you have taken from here: http://stackoverflow.com/questions/3572463/what-is-context-on-android – Mick Dec 28 '16 at 02:29
  • 1
    @Mick hm. I translated this text from Russian source. It's seems to me very funny. BTW, Ok I put the related link. – Sergey Shustikov Dec 28 '16 at 02:33
11

Activity is a subclass of Context, so whenever a context is required, either can be given.

getActivity() is at least a method on Fragment, to get the activity it is attached to.

Whenever a context is needed in an instance method of an activity, you can use this.

A context is needed whenever contextual info is needed, or when stuff needs to be displayed.

wvdz
  • 16,251
  • 4
  • 53
  • 90
0

getContext():

It is a method in the View class, which can be accessed only in the class that inherits from the View class, and returns what Activity Context the current View is running in.

getActivity():

Returns the Activity object to which the Fragment is attached. The reason why getActivity() in Fragment is not recommended is as follows: This method will return the Activity attached to the current Fragment. When the Fragment life cycle ends and is destroyed, getActivity() returns null, so one needs to handle the null cases which might arise while using getActivity() .

Anubhav
  • 1,984
  • 22
  • 17