2

Can someone help me with how to add my JSON values to the list? I can't seem to insert it despite putting List.add() function. It's my first time on tinkering JSON stuff in Android. I really appreciate the help.

P.S: somehow, the "API CALL SUCCESS" toast was triggering but the values that I extract won't add in the List.

UPDATE: Still can't find a fitting implementation.

    fun createDataset(): ArrayList<ItemPost>{
    val url = "http://api.karawcraftventure.com/item"
    val list = ArrayList<ItemPost>()
     val Queue = Volley.newRequestQueue(activity)
    val jsonObject = JsonArrayRequest(
        Request.Method.GET,url,null,
        {response ->
            Toast.makeText(context, "API CALL SUCCESS", Toast.LENGTH_SHORT).show()
            try
            {
                for (i in 0 until response.length())
                {
                    val item : JSONObject = response.getJSONObject(i)
                    val API_Image : String = item.getString("product_image").
                    val API_ItemName : String = item.getString("product_name")
                    val API_Price : String = item.getString("product_price")
                    val API_Category : String = item.getString("product_category")
                    list.add(
                        ItemPost(
                            API_Image,
                            API_ItemName,
                            API_Category,
                            API_Price
                        )
                    )
                }

            }
            catch (e: JSONException)
            {
                e.printStackTrace()
            }
        },
        { error: VolleyError? -> Toast.makeText(context, error?.message.toString(), Toast.LENGTH_SHORT).show()

        }
    )
     Queue.add(jsonObject)
     return list
}
Apprent1ce
  • 25
  • 6
  • I'll check this out sir. P.S: Just checked it out no, unfortunately. :( – Apprent1ce Nov 05 '21 at 00:34
  • Above question is just one of many similar questions. Generally, what you're trying to achieve here is to return a value acquired inside a callback. This is not directly possible, but there are some ways to do it. If solutions in above question are not enough, try looking for "kotlin return callback". – broot Nov 05 '21 at 00:37
  • Will do sir. I'll update later if I manage to see something similar in my situation. – Apprent1ce Nov 05 '21 at 00:38
  • can you put a Log msg inside loop and a log msg just before adding into the list and after that as well. So that we can see wether its inside the loop or not. and does it reaching the list.add line @W.DGaster – Noman khanbhai Nov 05 '21 at 09:53
  • I checked it using toast notif, it was reaching before and after the list.add but the values is still not inserting. – Apprent1ce Nov 05 '21 at 11:08

0 Answers0