Rod
Rod

Reputation: 752

How to properly use the URL with Kotlin Android

I want to use

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val json = URL("https://my-api-url.com/something").readText()
    simpleTextView.setText(json)
}

but this fatal error occurs

FATAL EXCEPTION: main
    Process: com.mypackage.randompackage, PID: 812
    java.lang.RuntimeException: Unable to start activity ComponentInfo{ ***.MainActivity}: android.os.NetworkOnMainThreadException

How can I simply read a JSON from a URL link? The package of the async function doesn't exist.

Upvotes: 3

Views: 12721

Answers (2)

Bohsen
Bohsen

Reputation: 4350

You could use coroutines:

val json = async(UI) {
        URL("https://my-api-url.com/something").readText()
    }

Remember to add coroutines to build.gradle:

kotlin {
experimental {
        coroutines "enable"
    }
}
...
dependencies {
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlinx_coroutines_version"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$kotlinx_coroutines_version"
...
}

Coroutines are brilliant.

Upvotes: 2

Marko Devcic
Marko Devcic

Reputation: 1101

Android doesn't allow accessing the internet from the main thread. The simplest way around this would be to open the URL on a background thread.

Something like this:

Executors.newSingleThreadExecutor().execute({
            val json = URL("https://my-api-url.com/something").readText()
            simpleTextView.post { simpleTextView.text = json }
        })

Don't forget to register Internet permission in the Android Manifest file.

Upvotes: 9

Related Questions