0

I want to know the difference between the two contexts in the two Toasts below , when to use this & when to use getActicity ?

   Toast.makeText(getActivity() , "Text" ,Toast.LENGTH_LONG).show();

   Toast.makeText(this , "Text" ,Toast.LENGTH_LONG).show();
Mohammad
  • 1
  • 1
  • 3
    Possible duplicate of http://stackoverflow.com/questions/10347184/difference-and-when-to-use-getapplication-getapplicationcontext-getbasecon – Harsh Dattani May 17 '15 at 17:56
  • 2
    `getActivity()` is used when you are out of the context (i.e.: in a Fragment), where `this` won't work. – Phantômaxx May 17 '15 at 17:56

4 Answers4

1

If you say are trying to access it from a Fragment, use getActivity() else if you are in Activity itself, use this.

Mithun
  • 2,075
  • 3
  • 19
  • 26
1

You can specify your Context with this or getApplicationContext() with Activities.

getActivity() 

is used with Android Fragments

Don Chakkappan
  • 7,397
  • 5
  • 44
  • 59
1

this is actually a pointer that refers to the current class that you are in. this can refer to anything like Activity, Fragment, View, etc.A reference of the current object is passed while this is used.

getActivity() is available only in the Fragment class and any other class extending Fragment and this method returns an object of the type Activity.

Lal
  • 14,726
  • 4
  • 45
  • 70
1

To create a Toast you need a Context object.

If you are in an Activity class or another class that extends the Context class you can use this (because the Activity is itself a Context child )

If you are for example in a Fragment class, that doesn't extends Context, you should use getActivity() to get a Context reference.

Here the docs about the Context class where you find all the classes that extends it : http://developer.android.com/reference/android/content/Context.html

user1305336
  • 151
  • 1
  • 1
  • 12