2

I am using static factory method to create fragment. But I need to use activity's context in the fragment and therefore I need to wrap that context into a bundle and attach it to the fragment using setArguements() method so that I can retrieve it later.

But if I try to store context by doing bundle.putSerializable("tag", context) -> it throws an error. Can anyone tell me how to wrap activity context into a bundle?

allstraws
  • 129
  • 3
  • 12

1 Answers1

10

But I need to use activity's context in the fragment

You do not need it in most cases. All you need is to use getActivity() in your fragment instead.

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
  • does that mean we never need to pass any context to a fragment because it can always be obtained through getActivity()? – allstraws Jul 16 '15 at 13:36
  • 1
    @allstraws see this question on how to get context in a fragment http://stackoverflow.com/questions/8215308/using-context-in-fragment – tyczj Jul 16 '15 at 13:38
  • 1
    @allstraws you cannot get it always (i.e. you won't get it in your `getInstance()` implementation or constructor), but you basically need activity only when you are part of it, and in such case `getActivity()` is what you are looking for. – Marcin Orlowski Jul 16 '15 at 13:55