0

Hello I am noob in android. I see that in android you can get context using different method. I could not understand the difference between them and when to use what .

Methods : getApplicationContext(), getContext(), getBaseContext(), this (Activity)

Mick
  • 1,179
  • 5
  • 14
  • 24
  • 1
    Did you already read the documentation? https://developer.android.com/reference/android/content/Context.html#getApplicationContext() – donfuxx Apr 14 '14 at 18:54
  • Yes I have already wrote in the question **I could not understand the difference between them** – Mick Apr 14 '14 at 18:55
  • 2
    But you never told us what definitions you were basing your understanding off. It was a valid inquiry.. – indivisible Apr 14 '14 at 18:58
  • 1
    To sum it up: It's whole application lifetime vs. activity lifetime – donfuxx Apr 14 '14 at 19:01
  • @donfuxx so getContext(), getBaseContext(), this (Activity) does same - activity lifetime ?? – Mick Apr 14 '14 at 19:01
  • 2
    take a look at the answers of this related question: http://stackoverflow.com/a/10347346/2399024 – donfuxx Apr 14 '14 at 19:19

1 Answers1

2

An 'Application context' is associated with the Application and will always be the same throughout the life cycle of your app (getApplicationContext())

The 'Activity context' is associated with the activity and could possibly be destroyed many times as the activity is destroyed during screen orientation changes and such.(getContext())

Generally don't use getBaseContext(), rather use one of the previous ones as needed.

You might want to use the Application Context (Activity.getApplicationContext()) rather than using the Activity context (this). This is because 'this' needs to be called from within an Activity. (Activity extends Context )

Ushal Naidoo
  • 2,704
  • 1
  • 24
  • 37
  • Generally don't use getBaseContext(), rather use one of the previous ones as needed. Why ?? – Mick Apr 15 '14 at 05:31
  • getBaseContext() is the method of ContextWrapper – Ushal Naidoo Apr 17 '14 at 08:47
  • so what ContextWrapper do if I use getBaseContext ?? – Mick Apr 17 '14 at 12:17
  • If you need access to a Context from within another context, you use a ContextWrapper. The Context referred to from that ContextWrapper is accessed with the getBaseContext() http://developer.android.com/reference/android/content/ContextWrapper.html#getBaseContext%28%29 – Ushal Naidoo Apr 21 '14 at 21:06
  • What mean of context from within another context and what this is use for ? You gave nice answer yet I will surely accept your answer – Mick Apr 24 '14 at 11:50
  • It could be used for such elements as inflating a view from within a context or for an Async class. However the use of getApplicationContext() is better as it is more explicit – Ushal Naidoo Apr 25 '14 at 03:08