In some places we were giving like “DatabaseUtil db=new DatabaseUtil(DailyPlanView.this);” where DatabaseUtil is the class with the constructor argument is context. But if we create the object for the DatabaseUtil class in the DailyPlanVIew class we are using the above code. My doubt is what is the use of the context and instead of passing the context object as argument why we are passing “this”.
In some places we were giving like DatabaseUtil db=new DatabaseUtil(DailyPlanView.this); where DatabaseUtil is the
Share
Whenever you are dealing with Context, its important to understand its used in everything. From using a database to obtaining system services. This is required by the way android works with Context. Specifically when you are passing
thisyou are basically passing the class that encapsulates this statement.passing
thisrefers to the object that encapsulates it. This is a Object oriented concept… Wherethisis reffering toMyActivity. One thing to keep in mind when passing context is ensure that you are passing the correct kind. Some Context objects have a longer lifespan than others and if not managed properly can lead to Context leaking. Specifically in this example, this works because Activity extends Context.The differences occur in the View class.
getApplicationContext()getBaseContext()this, which in the Context of an activity has the life span of an Activity (Example above)One thing to add about Context is that it is basically a reference to the current Application and it’s specific data.
Some more information about context can be found in this thread:
What is 'Context' on Android?