0

In my main activity, I'm using navigation component to switch between the fragments,

I'm fetching data from my backend, the data received successfully then I'm updating my UI, I'm getting this error for one of my fragment,

for this code

 Converters.getSpannableString(
                    ""name,
                    0,
                    2,
                    ContextCompat.getColor(
                        requireActivity(),
                        R.color.lightSpanRed
                    )



on this line I'm getting crash:- ContextCompat.getColor(requireActivity(),R.color.lightSpanRed)

the Logs is

java.lang.IllegalStateException: Fragment MainFragment{ce669b1} (aa1b0f2b-de44-443a-834e- 
ee9e10df261b)} not attached to an activity.
    at androidx.fragment.app.Fragment.requireActivity(Fragment.java:833)

I'm getting this error, can anyone provide the best answer

1 Answers1

1

You must check the method in which you are executing this code.

You can use requireContext() instead of requireActivity.

Or

You can safely unwrap it is specified in the comments.

activity?.let {
            Converters.getSpannableString(
                "",
                0,
                2,
                ContextCompat.getColor(
                    it,
                    R.color.colorPrimaryDark
                )
            )
        }
  • 2
    This is treating the symptom of the problem, but not the root cause. If any callback is happening after the fragment is detached from the activity, that's already a memory leak and bigger problem that needs to be fixed. Fixing that root issue would make this covering up of the larger issue irrelevant. – ianhanniballake Jan 29 '21 at 06:11
  • You can use `lifecyclescope` for that. – Himanshu Choudhary Jan 30 '21 at 05:49