android
runtime_error
ai_generated
true
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
80%Fix Rate
82%Confidence
1Evidence
2024-01-10First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| Android 10 (API 29) | active | — | — | — |
| Android 11 (API 30) | active | — | — | — |
| Android 12 (API 31) | active | — | — | — |
Root Cause
NetworkCallback instance is null when ConnectivityManager triggers the callback, often due to premature unregistration or lifecycle mismanagement.
generic中文
当 ConnectivityManager 触发回调时 NetworkCallback 实例为 null,通常是由于过早取消注册或生命周期管理不当。
Official Documentation
https://developer.android.com/reference/android/net/ConnectivityManager.NetworkCallbackWorkarounds
-
90% success Check callback for null before unregistering: `if (networkCallback != null) { connectivityManager.unregisterNetworkCallback(networkCallback); }`
Check callback for null before unregistering: `if (networkCallback != null) { connectivityManager.unregisterNetworkCallback(networkCallback); }` -
85% success Use a WeakReference to hold the callback: `private var callbackRef: WeakReference<NetworkCallback>? = null` and check `callbackRef?.get()` before use.
Use a WeakReference to hold the callback: `private var callbackRef: WeakReference<NetworkCallback>? = null` and check `callbackRef?.get()` before use.
-
88% success In Activity onStop(), set a flag and delay unregistration until onDestroy() with null check: `if (isCallbackRegistered && networkCallback != null) { ... }`
In Activity onStop(), set a flag and delay unregistration until onDestroy() with null check: `if (isCallbackRegistered && networkCallback != null) { ... }`
中文步骤
Check callback for null before unregistering: `if (networkCallback != null) { connectivityManager.unregisterNetworkCallback(networkCallback); }`Use a WeakReference to hold the callback: `private var callbackRef: WeakReference<NetworkCallback>? = null` and check `callbackRef?.get()` before use.
In Activity onStop(), set a flag and delay unregistration until onDestroy() with null check: `if (isCallbackRegistered && networkCallback != null) { ... }`
Dead Ends
Common approaches that don't work:
-
Wrap callback call in try-catch NullPointerException
90% fail
Silently swallows the error but doesn't fix the root cause; callback may never fire again.
-
Register callback in Application.onCreate()
75% fail
Application context may outlive Activity; callback still null if unregistered incorrectly.
-
Use HandlerThread for callback registration
85% fail
Threading doesn't prevent null reference; the issue is lifecycle, not threading.