How to Fetch Data from API in Android Studio
How to Fetch Data from API in Android:
Kotlin provides some extension functions that will make requests much simpler. First, we’re going to create a new Request class:
class Request(val url: String) { fun run() { val forecastJsonStr = URL(url).readText() Log.d(javaClass.simpleName, forecastJsonStr) } }
The constructor simply receives a URL. Then the run function reads the result and outputs the JSON in the Logcat.
The implementation is really easy when using readText, an extension function from the Kotlin standard library. This method is not recommended for huge responses, but it will be good enough in our case.
If you compare this code with the one you’d need in Java, you will see we’ve saved a huge amount of overhead just using the standard library. An HttpURLConnection, a BufferedReader and an iteration over the result would have been necessary to get the same result, apart from having to manage the status of the connection and the reader. That’s what the function is doing behind the scenes, but we have it for free.
To be able to perform the request, the App must use Internet permission. So it must be added to the AndroidManifest.xml