Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

android - I'm getting "not attached to an activity" error

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

question from:https://stackoverflow.com/questions/65949126/im-getting-not-attached-to-an-activity-error

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
                )
            )
        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...