Chema
Chema

Reputation: 15

Error Fragment not attached to an activity when I leave a fragment and enter it again

When I change the fragment and return to the one that was at the beginning, running a line I get the error Fragment not attached to an activity. It is strange because before I get to this line, I use requireAcitivity() and it works fine. The error appears after calling an ArrayAdapter custom

When I call the arrayadapter, the requiredActivity method still works:

val adapter = ListUserGameInfoAdapter(requireContext(), gameViewModel!!)
gameInfoListUsers.adapter = adapter

Each row of the list created by the arrayAdapter has a button.

icon.setOnClickListener {
     gameViewModel.userToDeleteFromGamePositionLiveData.value = position
}

The button changes the value of a LiveData of the viewModel. By using an observer I pick up this new value of the LiveData. Inside the code of the observer, if I call requiredActivity(), the following error appears

        val userToDeleteObserver = Observer<Int> {
            if (it != null) {

                //If I call requiredActivity here, I get the error Fragment not attached to an activity

                showDialog(it)
            }
        }
        gameViewModel!!.userToDeleteFromGamePositionLiveData.observe(
            requireActivity(),
            userToDeleteObserver
        )

The strange thing is that the first time I enter this fragment the error does not appear, only when I go to another one and come back to this one.

Upvotes: 0

Views: 985

Answers (1)

Henry Twist
Henry Twist

Reputation: 5980

You're adding an observer in your fragment, but tying it to the lifecycle of your activity. Therefore it will keep observing for changes even when the fragment has been destroyed, which is why you're getting a crash when calling requireActivity() in your observer.

If you do some debugging, you'll probably notice that the observer is actually triggering twice, once for the old fragment (no longer attached to an activity) and once for the new fragment.

You should be using Fragment.getViewLifecycleOwner() instead.

Upvotes: 3

Related Questions