首页 > 解决方案 > Android 自定义适配器越界异常

问题描述

在 Kotlin 中编写一个 android 应用程序时,我遇到了这个错误: 在此处输入图像描述

我正在使用OpenWeatherMapApi并尝试从 API 中获取预测数据。由于 okhttp3 和 Gson,我能够提取预测数据,但现在我的问题是显示该数据。我为自定义 ArrayAdapter 创建了一个新类,我尝试在我创建的 textView 中显示,但我完全不知道为什么我不断收到错误数组的大小不应该为 1 但它结束了拥有它

代码

import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.weather_row.view.*

class ForecastAdapter(val forecast: Forecast) : RecyclerView.Adapter<ForecastData>(){

    override fun getItemCount(): Int {
        return forecast.list.count()

    }

    override fun onCreateViewHolder(p0: ViewGroup, p1: Int): ForecastData {
        val layoutInflator = LayoutInflater.from(p0?.context)
        val cellForRow = layoutInflator.inflate(R.layout.weather_row, p0, false)
        return ForecastData(cellForRow)

    }

    override fun onBindViewHolder(p0: ForecastData, p1: Int) {
        val getWeather = forecast.list[p1]
        val  clouds = getWeather.weather[p1]
        p0.view.textView_text_clouds.text = clouds.main
    }

}

class ForecastData(val view: View): RecyclerView.ViewHolder(view){


}

标签: androidkotlinandroid-arrayadaptercustom-arrayadapter

解决方案


你的问题是

getWeather.weather[p1]

weather列表”并不是真正的列表。它通常只有一个元素。

改用这个:

getWeather.weather[0]

推荐阅读