# java.lang.NullPointerException: Attempt to invoke virtual method 'void android.net.ConnectivityManager$NetworkCallback.onAvailable(android.net.Network)' on a null object reference

- **ID:** `android/connectivity-manager-network-callback-null`
- **Domain:** android
- **Category:** runtime_error
- **Verification:** ai_generated
- **Fix Rate:** 80%

## Root Cause

NetworkCallback instance is null when ConnectivityManager triggers the callback, often due to premature unregistration or lifecycle mismanagement.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| Android 10 (API 29) | active | — | — |
| Android 11 (API 30) | active | — | — |
| Android 12 (API 31) | active | — | — |

## Workarounds

1. **Check callback for null before unregistering: `if (networkCallback != null) { connectivityManager.unregisterNetworkCallback(networkCallback); }`** (90% success)
   ```
   Check callback for null before unregistering: `if (networkCallback != null) { connectivityManager.unregisterNetworkCallback(networkCallback); }`
   ```
2. **Use a WeakReference to hold the callback: `private var callbackRef: WeakReference<NetworkCallback>? = null` and check `callbackRef?.get()` before use.** (85% success)
   ```
   Use a WeakReference to hold the callback: `private var callbackRef: WeakReference<NetworkCallback>? = null` and check `callbackRef?.get()` before use.
   ```
3. **In Activity onStop(), set a flag and delay unregistration until onDestroy() with null check: `if (isCallbackRegistered && networkCallback != null) { ... }`** (88% success)
   ```
   In Activity onStop(), set a flag and delay unregistration until onDestroy() with null check: `if (isCallbackRegistered && networkCallback != null) { ... }`
   ```

## Dead Ends

- **Wrap callback call in try-catch NullPointerException** — Silently swallows the error but doesn't fix the root cause; callback may never fire again. (90% fail)
- **Register callback in Application.onCreate()** — Application context may outlive Activity; callback still null if unregistered incorrectly. (75% fail)
- **Use HandlerThread for callback registration** — Threading doesn't prevent null reference; the issue is lifecycle, not threading. (85% fail)
