0

In my app, I am using OkHttpClient to send a simple HTTP request to a webserver and get a String response back. I was able to verify that the following code works. However, I can't display the received response in a Toast message box. If I try to do that, my app completely crashes. Without the Toast, app runs with no problem.

        val myURL: String = "MyURL"

        //creating request
        val request = Request.Builder()
            .url(myURL)
            .build()

        if (myURL.isNotEmpty()) {
            val client = OkHttpClient();
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    Toast.makeText(this@MainActivity, e.printStackTrace().toString(), Toast.LENGTH_SHORT).show()
                }

                override fun onResponse(call: Call, response: Response) {
                    Toast.makeText(this@MainActivity, response.body.toString(), Toast.LENGTH_SHORT).show()
                }
            })
        }

LogCat: java.lang.NullPointerException: Can't toast on a thread that has not called Looper.prepare()

android.os.NetworkOnMainThreadException

Any idea?

1
  • Use Logcat to examine the stack trace associated with your request. Commented Dec 30, 2024 at 20:27

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.