Fragment not attached to a context 🤖 Android

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

  1. Launch work in viewLifecycleOwner.lifecycleScope
  2. Check isAdded before using context
  3. Cancel callbacks in onDestroyView

Detailed fix by platform

Kotlin

  1. kotlin
    viewLifecycleOwner.lifecycleScope.launch {
        val data = repo.load()
        if (isAdded) binding.title.text = getString(R.string.loaded, data.name)
    }

How to diagnose

  1. Callback — Which async call?
  2. 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:

🧠 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.