0

I have read many tutorials that describes the difference between android various options to get Context but I am still in Confusion. Is there any problem If i used getApplicationContex() instead of getContext(),this,getActivity() and getBaseContext().. In my entire Application?

Many people marked this Question as duplicate. But still I didn't got the satisfied answer from anyone. The answer should be in Yes or No and if Yes then the proper reason for that.

Please have a look to my Question once again.

Is there any problem If i used getApplicationContex() instead of getContext(),this,getActivity() and getBaseContext() etc etc... In my entire Application? If Yes.. Why?

Mehboob Maniyar
  • 238
  • 1
  • 3
  • 11

2 Answers2

0

Most of the time the context that you get is the Activity not the Application. Here is a nice explanation about the Contexts.
As far as I think, if I need anything to do with UI, I use the Activity context.

yadav_vi
  • 1,289
  • 4
  • 16
  • 46
0

Context is the main base class in Android Library. Every class extends it. It is just like Object class in Java Library.

There are different ways of getting Context

  • getApplicationContext() : It points to application's context.
  • getContext() : It points to current running component.
  • getBaseContext() : It is the method of ContextWrapper. And ContextWrapper is, "Proxying implementation of Context that simply delegates all of its calls to another Context. Can be subclassed to modify behavior without changing the original Context." (as per javadocs).
  • this : It points to current Activity/BroardcastReceiver or Service's context.
  • getActivity() : It points to current running activity's Context.
Lucifer
  • 29,392
  • 25
  • 90
  • 143
  • I got the Idea that getApplicationContext() will return this and getContext() will return this etc etc..... But I want to know Is there any problem if I used getApplicationContext() IN MY ENTIRE app?? – Mehboob Maniyar Apr 10 '14 at 12:24
  • getApplicationContext() always returns application's context which means it has whole application's context. So it's proper way to get context. In other case you may get `NullPointerException` – Lucifer Apr 10 '14 at 12:26
  • It means I can Use getApplicationContext() any where in application to get Context Right? If it so then what's the use of other way to get Contexts. I am sorry to ask this type of Question But what i can do am new to the android World – Mehboob Maniyar Apr 10 '14 at 12:32
  • You are correct, your observation is nice. But I believe there must me some reason for this. The reason could be heap memory size, execution time difference, etc.. – Lucifer Apr 10 '14 at 12:34
  • @AndroidStudentM, did you get my point ? – Lucifer Apr 10 '14 at 13:02