Q:

how to fix connectionManager.activeNetworkInfo must not be null ? using kotlin

i'm trying to check the connectivity and do some actions in each state but when i turn of the connection in my mobile the app crash and it give me this error 'cnxManager .activeNetworkInfo must not be null'
My code
private fun isConnected(webView: WebView){
    val cnxManager : ConnectivityManager = baseContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    val netInfo : NetworkInfo = cnxManager.activeNetworkInfo

    if (netInfo.isConnected && netInfo.isConnectedOrConnecting){
        cnx_failed.visibility=View.INVISIBLE
        webView.visibility=View.VISIBLE
    }else{
        webView.visibility=View.INVISIBLE
        cnx_failed.visibility=View.VISIBLE
    }
}

A:

This is due to what is called a "platform type" in Kotlin. Since getActiveNetworkInfo() is not annotated as @Nullable or @NonNull you can choose to declare it as either type. So both:
val netInfo: NetworkInfo = cnxManager.activeNetworkInfo

and 
val netInfo: NetworkInfo? = cnxManager.activeNetworkInfo

are valid declarations. However, as Markus mentioned this method can return null, so you should declare it as the latter (nullable type). Any time you're doing interop with Java platform types, you have to be sure you declare it correctly.
With this in mind, you could rewrite your code as:
private fun updateConnectionStatus(webView: WebView) {
    val cnxManager = baseContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

    // Declare as a nullable type
    val netInfo : NetworkInfo? = cnxManager.activeNetworkInfo

    // Safe check -- assigns to false if netInfo is null
    val connected = netInfo?.isConnectedOrConnecting ?: false
    cnx_failed.visibility = if (connected) View.INVISIBLE else View.VISIBLE
    webView.visibility = if (connected) View.VISIBLE else View.INVISIBLE
}

