0

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,

Ali A. Jalil
  • 873
  • 11
  • 25

2 Answers2

0

Make a base class includes an abstract method returns Map<String, String> named for example getConvertedParams. This method should convert itself to Map<String, String> like:

val params = HashMap<String, String>()
params["attribute1"] = attribute1
params["attribute2"] = attribute2
...
return params

Every request object should extends that base class and override that method. In getParams where you send request, call getConvertedParams for your generic request object.

override fun getParams(): Map<String, String> {
   val params = myObject.getConvertedParams()
   return params
}

Also do not forget to change the method signature

public fun <BaseClassName> push(context: Context, url: String, myObject: BaseClassName, completion: (response: String) -> Unit)
faranjit
  • 1,567
  • 1
  • 15
  • 22
  • I know this way but I want a way to convert any serializable object to `HashMap()` – Ali A. Jalil Aug 02 '19 at 09:11
  • Have you ever looked at [this](https://www.baeldung.com/jackson-map), [this](https://stackoverflow.com/questions/37024300/java-convert-instance-of-class-to-hashmap) or [this](https://www.mkyong.com/java/java-convert-object-to-map-example/)? If you had, didnt they work? – faranjit Aug 02 '19 at 11:04
0

Finally for any one may like to use this way, I rewrite function as below:

public fun <T> push(context: Context, url: String, myObject: T,myObjectType : Array<Field>, completion: (response: String) -> Unit) {

    val myObjectAsDict = HashMap<String, String>()
    val allFields = myObjectType //:Array<Field> = myObjectType!!::class.java.declaredFields
    for ( field in allFields) {
        if (!field.isAccessible) {
            field.isAccessible = true
        }


        val value = field.get(myObject)
        if (value != null)
        {
            if( field.name != "serialVersionUID") {
                myObjectAsDict[field.name] = value.toString()
            }
        }
    }

    println(myObjectAsDict)

    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 = myObjectAsDict
            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)
}

And using of it As below:

 var myClass = MyClass()
        VolleyFunctions.push(this,"URL",myClass, MyClass::class.java.declaredFields)
        {
                response->
            myClass = Gson().fromJson(response, MyClass::class.java)
            println("myClass.Name${myClass.name}")
        } 

Thanks faranjit for your answer and yours comments.

Ali A. Jalil
  • 873
  • 11
  • 25