I managed to make API call in my activity and it does show me API results in logcat but I can't figure out how to display those data in my view?
Sample data
Note: data are under data
array.
{
"data": [
{
"id": "0ade1bfb-6d02-4a1f-9cd4-dc88fa8aadbd",
"name": "a",
"photo": null
},
{
"id": "30a18b38-c563-4b3a-8c7d-af483c616e49",
"name": "b",
"photo": null
},
{
"id": "709804f8-e429-4c9d-b5cd-2cf3b2add98c",
"name": "c",
"photo": null
},
{
"id": "be204e7b-f1ab-45bc-a842-3d5f3f033381",
"name": "d",
"photo": null
},
{
"id": "cafd632d-d9ba-4617-8823-abc145a95e9c",
"name": "e",
"photo": null
}
],
"message": "Data are ready."
}
Activity
private val client = OkHttpClient()
override fun onCreate(savedInstanceState: Bundle?) {
//....
run("api_link")
}
fun run(url: String) {
val request = Request.Builder()
.url(url)
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {}
override fun onResponse(call: Call, response: Response) {
Log.d("results: ", response.body()!!.string()) // does return the data
// returning data in view?
}
})
}
Question
- How do I define what element to show the returned data?
- How do I loop those data? (what if returned data was object? like get post by id)
Update
I've made some changes to my code and now I'm getting org.json.JSONException: No value for services
code
fun run(url: String) {
val request = Request.Builder()
.url(url)
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {}
override fun onResponse(call: Call, response: Response) {
// added this part
val list: ArrayList<Service> = ArrayList()
getServices(response.body()!!.string(), list)
//
Log.d("results: ", response.body()!!.string())
// Getting view element
val textView: TextView = findViewById(R.id.recycler)
textView.text = list.toString()
}
})
}
fun getServices(response: String, list: ArrayList<Service>) { //service class
var jsonObject = JSONObject(response)
val jsonArray = jsonObject.getJSONArray("services")
for (i in 0 until jsonArray.length()) {
val jsonObject1 = jsonArray.getJSONObject(i)
var listingObject = Service( //service class
jsonObject1.getInt("id"),
jsonObject1.getString("name"),
jsonObject1.getString("image")
)
list.add(listingObject)
}
}
Then I've add sercive class like:
class Service ( val id: Int, val name: String?, val image: String?) {
}
any idea?