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,318
  • 15
  • 65
  • 110
Sudheesh
  • 379
  • 1
  • 3
  • 7

4 Answers4

37

getApplicationContext() can get the context value

alexandre-rousseau
  • 1,960
  • 25
  • 30
Durga
  • 1,171
  • 1
  • 12
  • 17
32

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
  • 3,966
  • 1
  • 31
  • 36
3

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

Community
  • 1
  • 1
Mudassir
  • 14,250
  • 8
  • 62
  • 86
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
  • 437
  • 5
  • 11