#Why does attempting to connect to a URL crash my app?

1 messages · Page 1 of 1 (latest)

midnight lagoon
#
var url = URI("https://google.com").toURL()
var openConnection = url.openConnection()
openConnection.connect()

It throws an IOException,
but it's not clear why it's not connecting.

terse socketBOT
#

<@&987246623988019200> please have a look, thanks.

midnight lagoon
#

IOException sounds like a filesystem problem imo...

#

maybe there's more information in the exception, i'll try catch it

#

android.os.NetworkOnMainThreadException

terse socketBOT
midnight lagoon
#

maybe i lack android permissions

#

no that didn't fix it

#

same problem still

subtle eagle
#

The exception is pretty self explanatory. You can't use the main thread for network operations. You can either create new thread or use coroutines.

midnight lagoon
#

maybe runBlocking

#

https://hmkcode.com/android/android-network-connection-httpurlconnection-coroutine/

or maybe this

 val result = withContext(Dispatchers.IO) {
           
           // HTTP GET request code... 

        }
terse socketBOT
midnight lagoon
#

ok I figured out doing

GlobalScope.launch {
..
}

seems to work

#

hmmm...... it might be working now

#

now i gotta find out how to get the response using the library

#

ok, this question is solved.

#

Thanks @subtle eagle