2

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.

Rod
  • 712
  • 2
  • 12
  • 36

2 Answers2

9

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.

Marko Devcic
  • 1,069
  • 2
  • 13
  • 16
  • In case anyone wanted to know what exactly to put into the Android Manifest file, this is what worked for me. It goes within the tags but outside the tag – Caveman Feb 07 '19 at 20:48
  • 2
    Nice simple solution without adding dependencies. Its pretty shocking how fragmented online docs are on trying to do something simple like this in kotlin - I tried to get anko and the kotlin coroutines to work without any success. – dodgy_coder Feb 16 '19 at 08:20
  • It's taken me hours to find a solution to my simple problem, this was it, thank you so much!! – Maff Jul 21 '19 at 11:51
2

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.

Bohsen
  • 4,242
  • 4
  • 32
  • 58