How to make an HTTP request in Android on Kotlin (Retrofit, OkHttp, Ktor)
Hello everyone! I just started learning Kotlin for Android and encountered a problem with making HTTP requests. I need to get data from a REST API (e.g., a list of users) and display it in a RecyclerView. I tried using the old AsyncTask, but everywhere they write that it is deprecated and cannot be used in new versions of Android.
Here is an example of my code that doesn't work:
```kotlin
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val url = "https://jsonplaceholder.typicode.com/users"
val result = URL(url).readText() // Throws NetworkOnMainThreadException
textView.text = result
}
}
```
I understand that
No answers yet.
Log in to leave an answer
Blogs