1

I saw many examples for how to get the Context in BaseFragment like this:

protected lateinit var ctx: Context

override fun onAttach(context: Context?) {
    super.onAttach(context)
    ctx = context!!
}

And then we can use the context instance in our other fragments that extend BaseFragment. One, two, three (it's offered to get Context from onViewCreated()) and so on. It looks like workaround.

I also had some cases when "fragment detached from Activity" exceptions occurred while using getActivity() or getContext() in Fragment.

So, what's the true way?

badadin
  • 507
  • 1
  • 5
  • 18

1 Answers1

1

You can't guarantee context to be 100% non null, this is why it is marked as nullable (?), so the 'workaround' you mentioned actually will cause exception in case the activity detached. To avoid it don't mark ctx:Context as lateinit var make it nullable protected var ctx:Context? = null and check it state each time you want use it.

Maksim Novikov
  • 835
  • 6
  • 18
  • It will be null even if I won't assign the null value in onDetach()? I mean that it's referenced to activities Context and will be not stored in my BaseFragment? And if activity detaches, my lateinit var will overwrite the value to null? – badadin Jan 27 '19 at 13:04
  • 1
    Yes, context is just a reference to Activity in this case and if activity die the context will die too no matter where it was stored. – Maksim Novikov Jan 27 '19 at 13:54
  • Thank you for comprehensive answer! – badadin Jan 27 '19 at 14:02