Code:
package com.example.json3
import android.os.AsyncTask
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import org.json.JSONObject
import java.io.IOException
import java.io.InputStreamReader
import java.lang.Exception
import java.net.HttpURLConnection
import java.net.URL
import android.widget.Toast
import java.io.BufferedReader
class MainActivity : AppCompatActivity() {
private var xmlString = ""
private val XML_URL = "https://www.yotamarker.com"
var XML_UR= "https://reqres.in/api/users/2"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
getDataJSON()
try {
Thread.sleep(6000)
} catch (e: InterruptedException) {
e.printStackTrace()
}
txt1.text = xmlString
}
fun getDataJSON() {
//we never use void in AsyncTask, we need to use Void
object : AsyncTask<Void, Void, String>() {
override fun doInBackground(vararg voids: Void): String {
//we need to open HTTP URL Connection to our desired URL (www.boi.org.il)
var connection: HttpURLConnection? = null
try {
connection = URL(XML_URL).openConnection() as HttpURLConnection
val buf = BufferedReader(InputStreamReader(connection.inputStream))
var line: String?
line = buf.readLine()
while (line != null) {
line = buf.readLine()
xmlString += line
}
} catch (e: IOException) {
e.printStackTrace()
} finally {
connection!!.disconnect()
}
return xmlString
}
override fun onPostExecute(jsonString: String) {
super.onPostExecute(jsonString)
http@ http://Log.e("XML", "onPostExecute: " + jsonString);
// display json string
Toast.makeText(applicationContext, jsonString, Toast.LENGTH_LONG).show()
}
}.execute()
}
}
in the manifest :
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
:chobit: