I work on developing an android app and I would like to make a generic function of volley post request, I write my function as bellow:
public fun <T> push(context: Context, url: String, myObject: T, completion: (response: String) -> Unit) {
val queue = Volley.newRequestQueue(context)
val sr = object : StringRequest(
Method.POST, url,
Response.Listener { response ->
println(response)
completion(response)
},
Response.ErrorListener { volleyError ->
Common.showVolleyError(volleyError, context)
}) {
override fun getParams(): Map<String, String> {
val params = myObject as HashMap<String, String>
return params
}
@Throws(AuthFailureError::class)
override fun getHeaders(): Map<String, String> {
val params = HashMap<String, String>()
params["Content-Type"] = "application/x-www-form-urlencoded"
params["X-Requested-With"] = "XMLHttpRequest"
return params
}
}
sr.retryPolicy = DefaultRetryPolicy(
0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
)
queue.add(sr)
}
What I enforce is How to convert my serializable object to a HashMap<String, String>()
, i.e. How to bind myObject
to getParams()
function,