# IllegalStateException: Fragment x not attached to a context / not attached to an activity

**Code:** `Fragment not attached to a context` · **Category:** Android · **Seen on:** Android

Code called requireContext()/requireActivity()/getString() after the Fragment was detached — usually in an async callback.

## 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

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/android/fragment-not-attached-to-context)
