我正在研究Kotlin开发的android应用程序,该应用程序需要API服务才能像Json一样获取其数据,我对API的请求很多,所以我尝试编写一个通用函数来从服务器检索数据并将其映射到自定义课上,我用Volley和Gson做到了,我的代码如下:
public fun <T> dec(context: Context, url: String, decodable:T,completion: (response: String) -> Unit) {
val request = StringRequest(Request.Method.POST, url,
Response.Listener { response ->
// Process the json
try {
println("response$response")
completion(response)
} catch (e: Exception) {
println("Exception: $e")
}
}, Response.ErrorListener {volleyError ->
println("Volley error: $volleyError")
Common.showVolleyError(volleyError,context)
})
request.retryPolicy = DefaultRetryPolicy(
DefaultRetryPolicy.DEFAULT_TIMEOUT_MS,
0,
1f
)
// Add the volley post request to the request queue
VolleySingleton.getInstance(context).addToRequestQueue(request)
}
当我如上所述编写时,我将其称为:
VolleyFunctions.dec(this, PublicVariabls.getAllNews(last_item_by_sort.toInt()), NewsItem()) { response ->
newsList.addAll(Gson().fromJson<ArrayList<NewsItem>>(response))
}
一切正常,但是当我将其更改为:
public fun <T> dec(context: Context, url: String, decodable:T,completion: (response: ArrayList<T>) -> Unit) {
...
completion(Gson().fromJson<ArrayList<T>>(response))
并按如下所示调用它:
VolleyFunctions.dec(this, PublicVariabls.getAllNews(last_item_by_sort.toInt()), NewsItem()) { newsItems ->
newsList = newsItems
那是行不通的,为了使它起作用,我可以在seconde方法中对代码进行哪些更改? 在此先感谢