Saravanapandi_PSP
Saravanapandi_PSP

Reputation: 351

Why are we using Context in creating object for other class in Android?

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".

Upvotes: 2

Views: 1434

Answers (1)

jtt
jtt

Reputation: 13541

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 this you are basically passing the class that encapsulates this statement.

class MyActivity extends Activity
{

     onCreate(Bundle bundle)
     {
        View v = new View(this);
     }
}

passing this refers to the object that encapsulates it. This is a Object oriented concept... Where this is reffering to MyActivity. 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?

Upvotes: 2

Related Questions