user741855
user741855

Reputation: 31

getting context in java android

hey i have an android application in which i monitor gmail server in a thread in background..this thread runs infinitely ...on getting a mail in the mailbox I have to make a toast..but i am not able to get the context of current activity(since there are multiple activities in the app)...how to get context of current running activity or may be application..getApplicationcontext gives null.

Upvotes: 3

Views: 24755

Answers (4)

Gangnus
Gangnus

Reputation: 24484

In toasts and listeners and everywhere, if you need to get resources, You could use

Resources.getSystem().getString(android.R.string.cancel)

It has absolutely universal placement, but supports only system resources.

Upvotes: 3

Dinesh Sharma
Dinesh Sharma

Reputation: 11571

Use this or getApplicationContext() to get the current context. For example,

Context mContext=this;

or

Context mContext=getApplicationContext();

If the actvity is any child Acivity of some tabHost, then try getParent().getApplicationContext() also.

Upvotes: 2

Aleadam
Aleadam

Reputation: 40401

If you're running an Activity or a Service, both are Context themselves, so calling this suffice. On any callback method for a listener, this will refer to the listener, not to the Activity. You can refer to the Context using any View:

Context context = myView.getContext();  

Upvotes: 10

Mark Mooibroek
Mark Mooibroek

Reputation: 7706

You can get the context of the Activity by calling on the Class name. For instance, if you Activity is called from inside MainActivity you can get the context by typing:

Context context = this;

Upvotes: 0

Related Questions