Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How bypass NetworkOnMainThreadException on Kotlin

Hi i starting with kotlin, now Android Studio 3.0 support it, but i don't know how do a simple Network request in another thread...

in java is very easy

new Thread(new Runnable() {
    @Override
    public void run() {
        //Do dome Network Request

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //Update UI
            }
        });
    }
}).start();

i know i can do a AsyncTask and blablabla... but i don't want that. I want a simple solution without creating extra classes and complex use case

Is this possible in Kotlin?

like image 624
jmtt89 Avatar asked Nov 21 '17 23:11

jmtt89


People also ask

How do you handle NetworkOnMainThreadException?

NetworkOnMainThreadException. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

How do you use kotlin runOnUiThread?

runOnUiThread runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.


1 Answers

All of the same classes and methods from Java and the Android SDK are available in Kotlin, so you can just use the exact same thing. The formatting is a bit nicer because of support for SAM constructors among other things.

Thread({
    //Do some Network Request

    runOnUiThread({
        //Update UI
    })
}).start()
like image 84
James McCracken Avatar answered Oct 14 '22 09:10

James McCracken