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());
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With