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.

Mike Baxter
  • 6,868
  • 17
  • 67
  • 115
Sudheesh
  • 379
  • 1
  • 3
  • 7

4 Answers4

37

getApplicationContext() can get the context value

alexandre-rousseau
  • 2,321
  • 26
  • 33
Durga
  • 1,191
  • 1
  • 12
  • 18
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

Abandoned Cart
  • 4,512
  • 1
  • 34
  • 41
3

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

Community
  • 1
  • 1
Mudassir
  • 13,031
  • 8
  • 59
  • 87
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.

Mar Bar
  • 477
  • 6
  • 11