Android Kotlin:如何统计单篇Post对应的Comments总数?
解决单篇Post评论总数统计问题
首先咱们先梳理下现有代码里的小问题,再一步步修改实现统计功能:
1. 修正数据解析的错误
你现在在同一个评论接口的响应里同时解析了Array<Comments>和Array<Posts>,这显然不对——评论的JSON数据里根本没有Post的字段,所以postDetail数组是无效的。其实你已经从intent里拿到了目标postId,完全不需要再解析Post数据,直接用这个传入的ID就行。
2. 添加计数逻辑实现统计
只需要初始化一个计数器变量,遍历评论数组时,每匹配到和目标postId一致的评论,就把计数器加1,循环结束后就能得到总数了。
修改后的完整代码
private fun fetchCommentJson() { val targetPostId = intent.getIntExtra(POST_ID, -1) // 先判断传入的postId是否有效,避免无效请求 if (targetPostId == -1) { toast("Invalid Post ID") return } val commentJsonData = commentsJSON val client = OkHttpClient() val request = Request.Builder().url(commentJsonData).build() client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call?, e: IOException?) { toast("Something went wrong fetching your data") } override fun onResponse(call: Call?, response: Response?) { val body = response?.body()?.string() ?: run { toast("Empty response data") return } val gson = GsonBuilder().create() // 只需要解析评论数组即可 val commentsDetail = gson.fromJson(body, Array<Comments>::class.java) runOnUiThread { // 初始化计数器 var commentCount = 0 // 遍历所有评论,统计匹配的数量 for (comment in commentsDetail) { if (comment.postId == targetPostId) { commentCount++ // 如果你还需要打印单条评论,可以保留这行 println(comment) } } // 这里输出统计结果,你也可以替换成显示到UI上 println("Post $targetPostId 的评论总数:$commentCount") // 比如显示到TextView:tvCommentCount.text = "评论数:$commentCount" } } }) }
额外优化建议
- 可以用Kotlin的集合函数简化计数逻辑,不用写for循环:
这行代码和之前的for循环计数效果完全一样,更简洁。val commentCount = commentsDetail.count { it.postId == targetPostId } - 增加了
targetPostId的有效性判断,避免传入无效ID时做无用功;同时处理了响应体为空的情况,让代码更健壮。
内容的提问来源于stack exchange,提问作者Kenan Karic
相关产品推荐
相关产品推荐

