Here I'm posting my code
Async Task Function
inner class GetAsyncTask : AsyncTask() {
override fun onPreExecute() {
// Before doInBackground
}
override fun doInBackground(vararg urls: String?): String {
var urlConnection: HttpURLConnection? = null
try {
val url = URL(urls[0])
urlConnection = url.openConnection() as HttpURLConnection
var inString = streamToString(urlConnection.inputStream)
publishProgress(inString)
} catch (ex: Exception) {
} finally {
if (urlConnection != null) {
urlConnection.disconnect()
}
}
return " "
}
override fun onProgressUpdate(vararg values: String?) {
try {
var json = JSONObject(values[0])
val query = json.getJSONObject("query")
val results = query.getJSONObject("results")
val channel = results.getJSONObject("channel")
val location = channel.getJSONObject("location")
val city = location.get("city")
val country = location.get("country")
val humidity = channel.getJSONObject("atmosphere").get("humidity")
val condition = channel.getJSONObject("item").getJSONObject("condition")
val temp = condition.get("temp")
val text = condition.get("text")
tvWeatherInfo.text =
"Location: " + city + " - " + country + "\n" +
"Humidity: " + humidity + "\n" +
"Temperature: " + temp + "\n" +
"Status: " + text
} catch (ex: Exception) {
}
}
override fun onPostExecute(result: String?) {
// Done
}
}
streamToString
fun streamToString(inputStream: InputStream): String {
val bufferReader = BufferedReader(InputStreamReader(inputStream))
var line: String
var result = ""
try {
do {
line = bufferReader.readLine()
if (line != null) {
result += line
}
} while (line != null)
inputStream.close()
} catch (ex: Exception) {
}
return result
}