How to get the current context?
Asked Answered
S

4

34

I want to use it in my array adapter. When I put this in a sub-activity to create an adapter it does not work.

Seamy answered 18/1, 2011 at 7:46 Comment(0)
R
37

getApplicationContext() can get the context value

Rajab answered 18/1, 2011 at 8:29 Comment(1)
This returns application context, not the current context, both are different.Canaan
D
33

You can get context a few ways:

By the Activity, using Your_Activity_Name.this

By the application, using getApplicationContext()

By the View, using Your_View.getContext()

The only one I would not recommend is using getBaseContext(). If you need something universal, have a public static variable in your main activity and assign the application context to it when your app starts. This way you can always call Your_Activity.your_context_variable

Demetria answered 9/1, 2013 at 7:12 Comment(0)
S
3

You can use getBaseContext() but this is not a local context.

Silvestro answered 18/1, 2011 at 7:49 Comment(0)
H
2

Besides the correct previous answers, you may want to think about refactoring your code if you've come to the point where you need to access "your" context from a sub activity. When you create a sub activity (ie: startActivityForResult) you are truly waiting for a result, not for an action in the caller activity. Then, when the sub activity has finished (and you have the result of its calculations), you can access your context in a proper way. It just doesn't seem fine that the subactivity is aware of its creator, not to mention interact with it.

Habitable answered 11/5, 2014 at 0:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.