Android App Fatal Exception on simple API call (Kotlin)

Viewed 32

I always got FATAL EXCEPTION when i try to make an API call. I made a button in the MainActivity, and setup an onClickListener:

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    
    override fun onCreate(savedInstanceState: Bundle?) {
        binding = ActivityMainBinding.inflate(layoutInflater)
                setContentView(binding.root)
                val sendbtn = binding.sendRequest
        sendbtn.setOnClickListener {
                fetchData().start()
        }
    }

And the function which is supossed to be called on click:

private fun fetchData(): Thread{
    return Thread {
        val url = URL("https://api.npoint.io/*********")
        val connection = url.openConnection() as HttpsURLConnection
        println(connection.responseCode.toString())
        if(connection.responseCode == 200) {
            val inputSystem = connection.inputStream
            val inputStreamReader = InputStreamReader(inputSystem, "UTF-8")
            val request = Gson().fromJson(inputStreamReader, Request::class.java)
            updateUI(request)
            inputStreamReader.close()
            inputSystem.close()
        }
        else{
            runOnUiThread {
                binding.nameText.text = "Failed connection"
            }
        }
    }

}

After i click the button the app exits with the following:

E/AndroidRuntime: FATAL EXCEPTION: Thread-2
    Process: com.example.myapicall, PID: 15357

I tried to add Internet Permission to the manifest.xml and with different URLs, but same result. The error occur on the "val connection" declaration because the println function never executes.

(i am a beginner in android apps and kotlin development, also this is my first question here, so if you are into virgins lend me a hand) Thank you!

0 Answers
Related