Get Value from Object to Activity/Fragment in Kotlin

29 views Asked by At

I have a goal here where I want to create a reusable volley service so I will not add those very long code on my activities. So far here`s what I did.

First I created an object

object APICallerUtils {
    fun callAPI(con: Context) {
        val cache = DiskBasedCache(con.cacheDir, 1024 * 1024)
        val network = BasicNetwork(HurlStack())
        val requestQueue = RequestQueue(cache, network).apply {
            start()
        }
        val builder: AlertDialog.Builder = AlertDialog.Builder(con)
        val dialog: AlertDialog = builder.create()

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            builder.setView(R.layout.layout_loading_dialog)
        }

        dialog.setCancelable(false)
        dialog.show()

        val stringRequest = object : StringRequest(Method.POST,
            "http://192.168.16.107/dynamicapicall/caller.php",
            Response.Listener { response ->
                try {
                    val obj = JSONObject(response)
                    //Log.e("Message",obj.toString())
                } catch (e: JSONException) {
                    val errorMessage = StringWriter()
                    //Log.e("Message",errorMessage.toString())
                }
                dialog.dismiss()
            },
            Response.ErrorListener { volleyError ->
                //Log.e("Message",volleyError.message.toString())
                dialog.dismiss()
            }) {
            @Throws(AuthFailureError::class)
            override fun getParams(): Map<String, String> {
                val params = HashMap<String, String>()
                return params
            }
        }
        requestQueue.add(stringRequest)
    }
}

And in my activity I call it like APICallerUtils.callAPI(this)

My question is the function returns a JSON how can I get that?

UPDATE Sorry for the confusion my goal here is to get the val obj = JSONObject(response) everytime I call APICallerUtils so I can assign it in a loop like

try {
     val obj = APICallerUtils 
     val array_drink_header = obj.getJSONArray("result")
     val DrinkHeader = ArrayList<drinkwall_header>()

      for (i in 0 until array_drink_header.length()) {
0

There are 0 answers