7

what is the correct usage of getActivity() and getApplicationContext() in fragment.

when getting an intent in fragment you use getActivity() and someplaces you use getAppliationContext();

getActivity() and getApplicationContext()

3iL
  • 2,146
  • 2
  • 23
  • 47
griffins
  • 7,079
  • 4
  • 29
  • 54

3 Answers3

19
getActivity()

This method gives the context of the Activity. You can use it is like the yourActivity.this. The method getActivity() is normally used in fragments to get the context of the activity in which they are inserted or inflated.

getApplicationContext()

Returns the context for the entire application (the process all the Activities are running inside of). Use this instead of the current Activity context if you need a context tied to the lifecycle of the entire application, not just the current Activity.

For more Info.

3iL
  • 2,146
  • 2
  • 23
  • 47
4

It seems like you need to refer some document for the use of both but It's okay you can start with below links.

getActivity() returns the Activity the fragment is associated with.

http://developer.android.com/reference/android/app/Fragment.html#getActivity()

getApplicationContext() returns the global Application context.

http://developer.android.com/reference/android/content/Context.html#getApplicationContext()

the application context should be used for functions like receivers, functions that should be destroyed when the application is destroyed, not when the activity is destroyed.

Dushyant Tankariya
  • 1,432
  • 3
  • 11
  • 17
2

getApplicationContext() used when you want the thing beyond the scope of your fragment or lets say activity .

While creating singleton object or initialising library we always stick to application context . If we tried using get activity here , it may lead to memory leaks.

coming to getActivity() ,this work as a context but it sticks to the life cycle of your fragment . While using this as context , always make sure to put check if this is null or not .

You can get the clear idea using below link : https://blog.mindorks.com/understanding-context-in-android-application-330913e32514

Mini Chip
  • 949
  • 10
  • 12