Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getBaseContext or getContext? How do they differ? [duplicate]

Tags:

java

android

I noticed that inside my class that extends View, to get the screen size I have to use getContext

DisplayMetrics dispM = getContext.getResources().getDisplayMetrics();
int width = dispM.WidthPixels;
int height = dispM.HeightPixels;

if I wanted to do the same inside my Activity, I have to replace getContext with getBaseContext. Why is this the case?

like image 992
Space Ghost Avatar asked Apr 11 '14 10:04

Space Ghost


People also ask

What is the difference between getContext () getApplicationContext () getBaseContext ()?

getApplicationContext() - Returns the context for all activities running in application. getBaseContext() - If you want to access Context from another context within application you can access. getContext() - Returns the context view only current running activity. Save this answer.

What is getBaseContext?

getBaseContext() is the method of ContextWrapper . And ContextWrapper is, "Proxying implementation of Context that simply delegates all of its calls to another Context. Can be subclassed to modify behavior without changing the original Context." (as per javadocs)..

What is the difference between this Context and getApplicationContext which one to use when?

You may wonder now, what is the difference between getContext() and getApplicationContext(). The difference is that Application's Context is not UI related. It means that, we shouldn't use it to Inflate a Layout, Start an Activity nor Show a Dialog.

Why do we use getContext in Android?

getContext(): It returns the Context which is linked to the Activity from which it is called. This is useful when we want to call the Context from only the current running activity.


2 Answers

View.getContext(): Returns the context the view is currently running in.

getBaseContext(): is the activity context itself. Even you can use this

like image 53
Zohra Khan Avatar answered Sep 20 '22 04:09

Zohra Khan


getContext() Returns the context the view is currently running in. . Activity.

getBaseContext() : If you need access to a Context from within another context, you use this

like image 24
Nirbhay Mishra Avatar answered Sep 21 '22 04:09

Nirbhay Mishra