Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Application Context to the view instead of Activity Context

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());
like image 238
user1041858 Avatar asked Nov 03 '22 07:11

user1041858


1 Answers

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.

like image 69
Sahil Mahajan Mj Avatar answered Nov 14 '22 23:11

Sahil Mahajan Mj