Android自定义适配器超出范围的异常

时间:2018-10-18 20:50:08

标签: android kotlin android-arrayadapter custom-arrayadapter

在Kotlin中编码一个Android应用程序时,我遇到了此错误: enter image description here

我正在使用OpenWeatherMapApi,并且正在从API中尝试获取“预测数据”。由于okhttp3和Gson,我能够提取Forecast数据,但是现在我的问题是显示该数据。我为自定义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){


}

1 个答案:

答案 0 :(得分:0)

您的问题在于

getWeather.weather[p1]

weather“列表”实际上不是列表。通常只有一个元素。

改为使用此:

getWeather.weather[0]