0

I have a problem with the navigation component. The problem is when call requireActivity, requireVIew and requireContext return Fragment not attached to an activity when executed this in onViewCreated. However, the problem is interesting because it does not occur all the time but in specific cases.

I have fragments A, B and C.

Application start, in fragment A i have a button to functionality, but first checking if user is signed in, if not, move to fragment B, if the user does not want to sign in or register, move from fragment B to fragment C. User can change fragments by BottomNavigation, so can move again to fragment A and try to sign in again in fragment B. Now, when user press button sign in application crash with information "Fragment not attached to an activity". Its odd, because when first time open fragment B and click sign in, its work normally, nothing crash. To open fragment B using

Navigation.findNavController(requireActivity(), 
R.id.nav_host_fragment).navigate(FragmantADirections.actionFragmentAToFragmentB(someData));

if user does not want to sign in and click back button using

OnBackPressedCallback callback = new OnBackPressedCallback(true) {
                @Override
                public void handleOnBackPressed() {
                    Navigation.findNavController(requireActivity(), R.id.nav_host_fragment).navigate(FragmantBDirections.actionFragmentBToFragmentC());

}};

enter image description here

Developer534255
  • 121
  • 1
  • 9
  • In many cases `requireActivity`, `requireContext` and similar, should be wrapped in something like `if (isAdded) { logic }`, in this way if the fragment or the activity are destroyed your callbacks will no try to call something which is detached or destroyed – MatPag Jun 03 '20 at 11:30
  • It looks as if the fragment was not connected to the view, but I can see it on the screen, the fragment's life cycle has been made, so requireActivity refers to the previous view? – Developer534255 Jun 03 '20 at 11:35
  • requireActivity refers to the activity which is hosting the fragment. Be sure to use AppCompatActivity or FragmentActivity as base Activity – MatPag Jun 03 '20 at 11:38
  • And in this case, NavigationController hosting only once this fragment? I dont understand where is the problem? Other fragments i use work normally with requireActivity or requireContext, always has it. – Developer534255 Jun 03 '20 at 11:43
  • I did not mention that I need to use it in the observer. So I create a field of the FragmentActivity type, I assign it in onCreateVIew, and it works otherwise, greetings from Google. I wonder why it works in such a way. – Developer534255 Jun 03 '20 at 11:59
  • You are probably using it in a wrong way. Search some tutorial online to see if you are doing the same thing – MatPag Jun 03 '20 at 14:30
  • Here is solution but not in navigation. You can achieve this when open fragments> https://stackoverflow.com/a/76137830/14566306 – TexD Apr 29 '23 at 18:45

0 Answers0