Home > Software engineering >  Kotlin not making request Volley - android
Kotlin not making request Volley - android

Time:07-17

I am trying to "dynamically" create CardView and then fill TextView with data from an API call. The thing is, to me it seems like the request is not getting called.

I created an adapter class based on Result1 empty

Update1:

class WeatherAdapter(context: Context, weatherModelArray: ArrayList<WeatherViewModel>):
    RecyclerView.Adapter<WeatherAdapter.ViewHolder>() {
    private val weatherModelArray: ArrayList<WeatherViewModel>

    // Constructor
    init {
        this.weatherModelArray = weatherModelArray
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WeatherAdapter.ViewHolder {
        val view: View = LayoutInflater.from(parent.context).inflate(R.layout.card_layout, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: WeatherAdapter.ViewHolder, position: Int) {
        val model = weatherModelArray[position]
        holder.apiName.text = model.apiName
        holder.apiResult.text = model.apiResult

    }

    override fun getItemCount(): Int {
        return weatherModelArray.size
    }

    inner class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
        val apiName: TextView
        val apiResult: TextView

        init {
            apiName = itemView.findViewById(R.id.idApiName)
            apiResult = itemView.findViewById(R.id.idApiResult)
        }
    }
}

CodePudding user response:

You need to notify the RecyclerView adapter that the data has changed after you change the data. This means calling notifyDataSetChanged from within the callback. That would look something like this:

internal fun apICall(context: Context, jsonView: WeatherViewModel, adapter: WeatherAdapter) {
    //...
    
    val stringRequest = StringRequest(
        Request.Method.GET, url,
        {response ->
            //...
            jsonView.apiResult = openJSON.daily[0].temp.toString()
            adapter.notifyDataSetChanged()
        },
        {
            jsonView.apiResult = "Error"
            adapter.notifyDataSetChanged()
        })

    // Add the request to the RequestQueue.
    queue.add(stringRequest) 
}
  • Related