Creating Extension [Kotlin] Error please help

Hi, my codes returning “Unknown Error” but why? Please help me

i tried without thread

    @SimpleFunction
    fun GetRecords() {

        val downloadUrl = "https://docs.google.com/spreadsheets/d/" + table_id + "/export?format=csv"
        
        Thread(Runnable {
            context.runOnUiThread {
                try {
                    val doc: Document = Jsoup.connect(downloadUrl).userAgent("Mozilla").get()
                    GotRecords(doc.outerHtml())
                } catch (e: Exception) {
                    ErrorOccurred(e.message ?: "Unknown Error")
                }
            }
        }).start()


    }

I guess its because of making network requests on UI thread. You can try to get the whole error instead of the message. So you would be able to check the error type and related properties.

2 Likes

i got “android.os.NetworkOnMainThreadException”

Instead of context.runOnUiThread, use context.runAsynchronously

1 Like

you are running request on UI thread instead of New thread/Async thread.

1 Like

this is not available

I am not familar with kotlin but the error simply mean you are running network operation on main thread.
You should look over to the documentation : Processes and threads overview | Android Developers

Basically when you launch your application, application create a primary thread which we called as main thread which is responsible for dispatching event to UI widgets and communicate with components. So, this is also called as UI thread. When we do heavy operations in Android, we should not perform that task on UI thread so we should create a new thread and perform task there. But to dispatch event, or i to associate result to UI thread, we use runOnUiThread method from Activity class.

Threads & Processes are related to each other so i will suggest you to read more about these terms from Android Developer Documentation.

An example of creating a new thread can be

Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                // Your code starts from here
            }
});
thread.start(); // To start the thread

Again, you should call runOnUiThread to send value to UI thread.

activity.runOnUiThread(new Runnable() { 
                        @Override
                        public void run() {
                            // Maybe raise a event or do something on UI thread
                        }
});

For examples for network operation like get request, you can read this thread from AppInventor Community :

2 Likes

It was very helpful. Thank you for your effort :sparkles::blush:

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.