Search code examples
android-livedataandroid-lifecycleandroid-contextlifecycleowner

requireActivity instead of requireContext in fragment


I am having a LiveData observer inside fragment, sometimes the code inside Observer{} throws error

Exception: java.lang.IllegalStateException: Fragment not attached to an activity.
at androidx.fragment.app.Fragment.requireActivity(Fragment.java:833)

It is happening because requireActivity() is returning null so the exception

myViewModel.saveData(data).observe(requireActivity(), Observer {
            it?.let { response->

                when(response.status){
                    Status.SUCCESS -> {
                       Toast.makeText(requireActivity(),"SUCCESS",Toast.LENGTH_LONG).show()
                    }
                    Status.ERROR -> {
                        Toast.makeText(requireActivity(),"ERROR",Toast.LENGTH_LONG).show()
                    }
                    Status.LOADING -> {
                    }
                }

            }
        })

I confirmed there is no scenario that my fragment being detached from the activity. I am suspecting the crash might be happening because I am not passing lifecycleowner reference to Observer?


Solution

  • Use ViewLifecycleOwner as LifecycleOwner while observing livedata from the fragment. Because the ViewLifecycleOwner is tied to the fragment's view lifecycle, but requireActivity() is tied to the fragment's overall lifecycle.

    myViewModel.saveData(data).observe(viewLifecycleOwner) {
            it?.let { response->
                when(response.status){
                    Status.SUCCESS -> {
                        Toast.makeText(requireActivity(),"SUCCESS",Toast.LENGTH_LONG).show()
                    }
                    Status.ERROR -> {
                        Toast.makeText(requireActivity(),"ERROR",Toast.LENGTH_LONG).show()
                    }
                    Status.LOADING -> {
                    }
                }
            }
        }