Kotlin: Checking network status using ConnectivityManager returns null if network disconnected. How come?

CEO tech4lifeapps picture CEO tech4lifeapps · Apr 13, 2018 · Viewed 11.4k times · Source

I try to check the status of my network (connected or disconnected) using this function:

// Check Network status
private fun isNetworkAvailable(): Boolean {
    val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE)
    return if (connectivityManager is ConnectivityManager) {
        val networkInfo = connectivityManager.activeNetworkInfo
        networkInfo.isConnected
    }
    else false
}

This gives me a java.lang.IllegalStateException: networkInfo must not be null - error when run with a disconnected network. Why? And how can I solve this?

Answer

Levi Moreira picture Levi Moreira · Apr 13, 2018

According to the docs activeNetworkInfo might be null:

Returns details about the currently active default data network. When connected, this network is the default route for outgoing connections. You should always check isConnected() before initiating network traffic. This may return null when there is no default network.

To make sure it doesn't crash, just use this:

 private fun isNetworkAvailable(): Boolean {
        val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE)
        return if (connectivityManager is ConnectivityManager) {
            val networkInfo: NetworkInfo? = connectivityManager.activeNetworkInfo
            networkInfo?.isConnected ?: false
        } else false
    }