Why getContext() in fragment sometimes returns null?

后端 未结 4 2170
栀梦
栀梦 2020-12-01 12:03

Why getContext() sometimes returns null? I pass context to LastNewsRVAdapter.java as an argument. But LayoutInflater.from(contex

4条回答
  •  我在风中等你
    2020-12-01 12:17

    When you are sure fragment is attached to its host(onResume, onViewCreated, etc) use this instead of getContext() :

    requireContext()
    

    It will not be inspected by lint, but it will throw an Exception if context detached!

    Then you should check nullity by if clouse (or some thing) or be sure that if the program reaches this line, it isn't null.

    In retrofit calls or retrofit (and may others in the same way), it will return a disposable that must be cleared or disposed before onDestroy.

提交回复
热议问题