I've been trying to validate the network connection status when a button is pressed. Hereby the code
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<Button>(R.id.button).setOnClickListener {
findViewById<TextView>(R.id.logText).setText("Button Pressed"+counter++)
GlobalScope.launch (Dispatchers.Main) {
val result = withContext(Dispatchers.Default){
isInternetAvailable()
}
println(result.toString())
}
}
}
suspend fun isInternetAvailable():Boolean {
return withContext(Dispatchers.Main) {
try {
val ipAddr = InetAddress.getByName("google.com")
//You can replace it with your name
println("1$ipAddr")
return@withContext !ipAddr.equals("")
} catch (e: Exception) {
println("within exception$e")
return@withContext false;
}
}
}
However, when the button is pressed following output can be seen in the console.
I/System.out: button clicked
I/System.out: within exceptionandroid.os.NetworkOnMainThreadException
I/System.out: false
Can someone please explain the reason for NetworkOnMainThread Exception?
Thanks a lot.