Home > Software engineering >  How to store retrofit2 API responses in an ArrayList and use it to populate recyclerView in Android
How to store retrofit2 API responses in an ArrayList and use it to populate recyclerView in Android

Time:01-01

How can I store responses from api to items array and use it latter

val items = ArrayList<ConvertedCurrency>()

for(curr in targetCurrencies) {
    val request = ServiceBuilder.buildService(ExchangeRateAPI::class.java)
    val call =
        request.getNewCurrency(etCurr.text.toString(), curr, etAmount.text.toString())

    call.enqueue(object : Callback<ConvertedCurrency> {
        override fun onResponse(
            call: Call<ConvertedCurrency>,
            response: Response<ConvertedCurrency>
        ) {
            if (response.isSuccessful) {
                textView.text = response.body()?.new_amount.toString()   response.body()?.new_currency
                val item = response.body() as ConvertedCurrency
                items.add(item) //adding responses to array

            }
        }

        override fun onFailure(call: Call<ConvertedCurrency>, t: Throwable) {
            TODO("Not yet implemented")
        }
        
    })
}

//I want to use that array here 
recyclerAdapter = CurrencyRecyclerAdapter(items)
currencyRecycler.apply {
    layoutManager = LinearLayoutManager(context)
    adapter = recyclerAdapter
}

When I run this in line where I initialize CurrencyRecyclerAdapter(items) the items array is empty

CodePudding user response:

enqueue method is called asynchronously, meaning that the code inside the enqueue method will be executed at some point in the future. Which means, you have set the adapter before the items array has been filled.

Try this :

val items = ArrayList<ConvertedCurrency>()

for(curr in targetCurrencies) {
    val request = ServiceBuilder.buildService(ExchangeRateAPI::class.java)
    val call =
        request.getNewCurrency(etCurr.text.toString(), curr, etAmount.text.toString())

    call.enqueue(object : Callback<ConvertedCurrency> {
        override fun onResponse(
            call: Call<ConvertedCurrency>,
            response: Response<ConvertedCurrency>
        ) {
            if (response.isSuccessful) {
                textView.text = response.body()?.new_amount.toString()   response.body()?.new_currency
                val item = response.body() as ConvertedCurrency
                items.add(item) //adding responses to array

                // Initialize the CurrencyRecyclerAdapter and set it as the adapter for the currencyRecycler view
                recyclerAdapter = CurrencyRecyclerAdapter(items)
                currencyRecycler.apply {
                    layoutManager = LinearLayoutManager(context)
                    adapter = recyclerAdapter
                }
            }
        }

        override fun onFailure(call: Call<ConvertedCurrency>, t: Throwable) {
            TODO("Not yet implemented")
        }
    })
}
  • Related