https://kotlinlang.org logo
#android
Title
# android
a

ar-g

03/28/2019, 11:28 AM
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

Alexander Johansson

03/28/2019, 11:58 AM
Probably because
isConnected
doesn’t necessarily return a true/false value.
Copy code
fun ConnectivityManager?.isConnected(): Boolean = this?.activeNetworkInfo?.isConnected ?: false
m

michelfernandez

03/28/2019, 1:13 PM
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

Paul Woitaschek

03/28/2019, 8:20 PM
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
9 Views