IllegalStateException: Fragment x not attached to a context / not attached to an activity
Code called requireContext()/requireActivity()/getString() after the Fragment was detached — usually in an async callback.
Seen on:
Android
Meaning
Network or database callbacks finishing after the user navigated away run against a detached fragment. Collect data with viewLifecycleOwner and check isAdded.
Common causes
- Async callback after onDetach/onDestroyView
- Using requireContext in a coroutine not tied to the view lifecycle
- Retained listeners
⚡ Quick fix
- Launch work in viewLifecycleOwner.lifecycleScope
- Check isAdded before using context
- Cancel callbacks in onDestroyView
Detailed fix by platform
Kotlin
- kotlin
viewLifecycleOwner.lifecycleScope.launch { val data = repo.load() if (isAdded) binding.title.text = getString(R.string.loaded, data.name) }
How to diagnose
- Callback — Which async call?
- Scope — lifecycleScope vs viewLifecycleOwner
🔧 Still not fixed?
Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:
Similar errors
- ActivityNotFoundException ActivityNotFoundException: Unable to find explicit activity class; have you declared this activity in your AndroidManifest.xml?
- adb unauthorized adb: device unauthorized. This adb server's $ADB_VENDOR_KEYS is not set
- Android resource linking failed AAPT: error: resource x (aka y) not found — Android resource linking failed
Most viewed in Android
Other ways to find it
🧠 Still stuck? Analyze your error
Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.
Was this page helpful?
Report a correction or suggest an improvement
Last updated 7 Oct 2026