hey, this code is throwing NPE, any ideas why? ``...
# android
a
hey, this code is throwing NPE, any ideas why?
Copy code
fun ConnectivityManager?.isConnected(): Boolean {
    return this != null && activeNetworkInfo != null && activeNetworkInfo.isConnected
}
Copy code
Fatal Exception: java.lang.IllegalStateException: activeNetworkInfo must not be null
a
Probably because
isConnected
doesn’t necessarily return a true/false value.
Copy code
fun ConnectivityManager?.isConnected(): Boolean = this?.activeNetworkInfo?.isConnected ?: false
m
a while ago I created a function similar to this ... I do not know if it helps you
Copy code
@RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
fun Context.isNetworkAvailable(): Boolean {
    return try {
        val manager = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
        val networkInfo = manager.activeNetworkInfo
        return networkInfo != null && networkInfo.isConnected
    } catch (tr: Throwable) {
        false
    }
}
p
activeNetworkInfo is not a captures variable but a synthetic accessor.
So you are actually calling
getActiveNetworkInfo()
twice.
The first time you check if it’s null and the second time you call the getter again and call
isConnected()
on it. It looks like the second time it returned null.
So the correct solution seems to be:
this?.activeNetworkInfo?.isConnected == true
👍 1
👏 1