5

Why use Activity Context while we can use Application Context to load and access resource? Means if I use Application Context instead of Activity Context there is no Exception occur so why use Activity Context?

Example:

In below example if I use getApplicationContext() instead of "this" pointer inside the Activities onCreate() it works fine without any exception.

 Button button = new Button(getApplicationContext());
Community
  • 1
  • 1
user1041858
  • 947
  • 2
  • 15
  • 32

2 Answers2

2

getApplicationContext() should be used with the view, which will be having scope outside the Activity (An example of it might be when you bind to a Service from an Activity).

But for Defining Views like as you mentioned above (to define a Button), you should Definitely use Activity's Context (MyActivity.this or Simply this).

The reason for it is if you use getApplicationContext(), it will live as longer as the Whole Application lives. But for a Button, it should destroy as soon the Activity finishes, So it is always better to use this(Activity's Context), when defining such type of Views.

if I use Application Context instead of Activity Context there is no Exception

There is no exception because both are valid Contexts. Its upon you that if you keep your view alive for entire application lifetime, even if it is not needed (which would ultimately lead to Memory Leakages), or you want to destroy it with as soon as the Activity finishes.

Sahil Mahajan Mj
  • 11,033
  • 8
  • 53
  • 100
  • 1
    I don't see how passing app context into view's constructor will extend it's lifetime beyond activity. The view is holding onto the app context reference and not the other way round, so as soon as the inflated layout, which is holding said view, is destroyed, the view should also be ready for GC unless you have another handle to it. – AAryz Jun 11 '18 at 10:18
0

They are both instances of Context, but the application instance is tied to the lifecycle of the application, while the Activity instance is tied to the lifecycle of an Activity. Thus, they have access to different information about the application environment.

If you read the docs at getApplicationContext it notes that you should only use this if you need a context whose lifecycle is separate from the current context. This doesn't apply in either of your examples.

The Activity context presumably has some information about the current activity that is necessary to complete those calls. If you show the exact error message, might be able to point to what exactly it needs.

But in general, use the activity context unless you have a good reason not to.

Sam-In-TechValens
  • 2,501
  • 4
  • 34
  • 67