如何在Android中获取API数据
我设法在我的活动中进行了API调用,它确实在logcat中向我显示了API结果,但我不知道如何在视图中显示这些数据如何在Android中获取API数据,android,kotlin,Android,Kotlin,我设法在我的活动中进行了API调用,它确实在logcat中向我显示了API结果,但我不知道如何在视图中显示这些数据 样本数据 注意:数据在数据数组下 { "data": [ { "id": "0ade1bfb-6d02-4a1f-9cd4-dc88fa8aadbd", "name": "a", "photo": null
样本数据
注意:数据在数据
数组下
{
"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."
}
活动
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?
}
})
}
问题
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)
}
}
有什么想法吗?从API接收数据和在UI上显示数据之间有一些步骤 你想怎么展示?填充回收视图?在toast中显示一些信息?在一些编辑文本中显示 您需要将JSON解析为某个对象,比如说对象“Data”,其中包含字段“id”、“name”和“photo” 在解析它之后,因为您已经在活动中,所以可以在视图中显示它 您需要获取视图的引用并显示它 如果您有编辑文本,可以通过调用以下命令来显示:
(your editText Reference).setText(data.name)
@一个本地人我不这么认为,no@mafortis尝试在需要解析的地方使用改型simpler@rcs我也安装了它,但从未提出过要求,所以我不知道怎么做?官方文件是一个很好的开始,我已经更新了我的问题(包括你的建议),你介意检查一下吗?@mafortis我建议你的“getServices”方法返回arrayList,这样您就可以编写list=getServices(…)。由于列表中有多个服务,因此无法在一个文本中显示所有内容。您可以通过以下方式测试代码:textView.text=list[0]。toString()。关于JSON错误,您可以在这里找到更多信息:不,不要搞错这些名称是我所做的许多更改留下的:D我实际上试图使用recycleview
findViewById(R.id.recycler)
我的意图是显示所有项目的列表。
(your editText Reference).setText(data.name)