Home > database >  Can someone teach me how to apply callbacks on my current code
Can someone teach me how to apply callbacks on my current code

Time:11-14

can someone teach me how to apply callbacks in my current code? I have tried applying it but I'm having a hard time understanding the concept easily. I have made an Interface that is needed for the callback but I don't know what to do next.

It's an API extracting code. The main idea of this code is to extract the data via volley then add it to the list which is the data source of my recyclerview.

    fun createDataset(): ArrayList<ItemPost>{
     val url = "http://api.karawcraftventure.com/item"
     // LIST DATA VARIABLE FOR RECYCLEVIEW
     val list = ArrayList<ItemPost>()
     // VOLLEY API REQUEST
     val Queue = Volley.newRequestQueue(activity)
     val jsonObject = JsonArrayRequest(
         Request.Method.GET,url,null,
         {response ->
             try
             {
                 for (i in 0 until response.length())
                 {
                     val item : JSONObject = response.getJSONObject(i)
                     val API_Image : String = item.getString("product_url_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")
                     // Toast Notif if data is extracted or not
                     //Toast.makeText(context, "$API_ItemName - $API_Price - $API_Category", Toast.LENGTH_SHORT).show()
                     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()

         }
     )
     // Sample Data for the list
     list.add(
         ItemPost("https://karawcraftventure.com/uploads/ONGLO_KC1.jpg",
             "Item Title1",
             "Item Category1",
             "Item Price1"
         )
     )
    list.add(
        ItemPost("https://karawcraftventure.com/uploads/ORIOL_KC.jpg",
            "Item Title2",
            "Item Category2",
            "Item Price2"
        )
    )
    list.add(
        ItemPost("https://karawcraftventure.com/uploads/ORIOL_KC.jpg",
            "Item Title3",
            "Item Category3",
            "Item Price3"
        )
    )
     list.add(
         ItemPost("https://karawcraftventure.com/uploads/ORIOL_KC.jpg",
             "Item Title4",
             "Item Category4",
             "Item Price4"
         )
     )
     Queue.add(jsonObject)
     return list
}

Here is the interface code that I created.

interface ItemCallback {
    fun GetItem(Ar: ArrayList<ItemPost>)
}

I have also posted a question before this but still not enough for me to come up with a solution.

JSON values won't insert in ArrayList

UPDATE: This is where I call the function CreateDataset():

private fun addDataSet()
{
    val data = createDataset()
    ItemAdapter.SubmitList(data)
}

Then addDataset() is called here.

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    initRecyclerView()
    addDataSet()
}

ItemRecyclerAdapter

fun SubmitList(ItemList : List<ItemPost>)
{
    Items = ItemList
}

FINAL SOLUTION

SOLVED BY ARPIT SHUKLA

createDataset function:

    fun createDataset(onSuccess: (List<ItemPost>) -> Unit){
     val url = "http://api.karawcraftventure.com/item"
     // LIST DATA VARIABLE FOR RECYCLEVIEW
     val list = ArrayList<ItemPost>()
     // VOLLEY API REQUEST
     val Queue = Volley.newRequestQueue(activity)
     val jsonObject = JsonArrayRequest(
         Request.Method.GET,url,null,
         {response ->
             try
             {
                 for (i in 0 until response.length())
                 {
                     val item : JSONObject = response.getJSONObject(i)
                     val API_Image : String = item.getString("product_url_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")
                     // Toast Notif if data is extracted or not
                     //Toast.makeText(context, "$API_ItemName - $API_Price - $API_Category", Toast.LENGTH_SHORT).show()
                     list.add(ItemPost(API_Image, API_ItemName, API_Category, API_Price))
                 }
                 onSuccess(list)
             }
             catch (e: JSONException)
             {
                 e.printStackTrace()
             }
         },
         { error: VolleyError? -> Toast.makeText(context, error?.message.toString(), Toast.LENGTH_SHORT).show()

         }
     )
     Queue.add(jsonObject)
}

SubmitList in Adapter

    fun SubmitList(ItemList : List<ItemPost>)
    {
        Items = ItemList
        notifyDataSetChanged()
    }

AddDataset function

private fun addDataSet()
    {
        createDataset {
            list -> ItemAdapter.SubmitList(list)
        }
    }

CodePudding user response:

Quick fix: Since you have everything inside one fragment, you can call ItemAdapter.SubmitList(data) inside createDataset when you receive the response.

fun createDataset() {
    ...
    { response ->
        try {
            for(...) {
                ...
                list.add(...)
            }
            ItemAdapter.SubmitList(list)
        } catch(...) {
            ...
        }
    }
    ...
}

private fun addDataSet() {
    createDataset()
}

Another approach: By passing a lambda callback:


```kotlin
fun createDataset(onSuccess: (List<ItemPost>) -> Unit) {
   ...
   for(...) {
       ...
       list.add(...)
   }
   onSuccess(list)
   ...
}

private fun addDataSet() {
    createDataset { list ->
        ItemAdapter.SubmitList(list)
    }
}

This approach is better than the previous one as now createDataset doesn't need a reference to the adapter.

Also, don't forget to call notifyDataSetChanged in you adapter inside SubmitList() to update your recycler view with new data

  • Related