Ammar Al-Kawaldeh
Ammar Al-Kawaldeh

Reputation: 37

makeText method , When to use this and When to use getBaseContext()

Hello all I have a problem in understanding context and using it in makeText

I saw many asks in this site and read about context in Android doc and using it in makeText method.But I am still not understanding many somethings :

*I read that the activity is a part of context but why we can't use MainActivity.class in the first parameter of makeText method and why this method need to context

sorry for the long questions but I'm really cant understand (Context)

Upvotes: 0

Views: 66

Answers (1)

Andrew Brooke
Andrew Brooke

Reputation: 12163

What is the deference between Activity and Context ?

As you can see in the Android reference, Activity is an indirect subclass of Context. (Activity extends Context). Essentially what this means is that Activities are 'Contexts', hence using this to get the context in an Activity.

Is the context means the current class ?

Not exactly. Context is literally the context of the application. It pertains to the current state of the application.

From the docs

It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.

Why I cant use this Instead of getBaseContext ?

If you are in an Activity, you can use this to reference the current Context, as Activity extends context.

Note that if you are in an inner class, such as an onClickListener, you will have to use YourActivity.this instead of this, to reference the context.

What is the deference between getBaseContext and getApplicationContext ?

Like the name suggests, getApplicationContext() returns the context that references the entire Application, and will be constant throughout any life cycle changes in the app.

getBaseContext() is a bit weirder. You can use it to access a context from inside another context, as detailed in this answer

For your purposes, (in Toast.makeText() ?), using YourActivity.this should work fine.

Upvotes: 1

Related Questions