@Override
public void onBindViewHolder(@NonNull MyViewHolder45 holder, int position)
{
AllClassDataResp allClassDataResp = allClassDataRespList.get(position);
int classNumb = allClassDataResp.getClassNum();
List<SectionInfo> list = allClassDataResp.getSectionInfos();
SectionInfo sectionInfo = list.get(position); // throwing IndexOutOfBounds Exception
String name = sectionInfo.getSectionName();
Long id = sectionInfo.getSectionId();
String classandSec = classNumb + "th" + " - " + name;
holder.tClassSec.setText(classandSec);
holder.sectionInfo = sectionInfo;
抛出IndexOutOfBoundsException。我也试过使用for循环但没有用。
我的Pojo课程。
public class AllClassDataResp {
@SerializedName("classNum")
@Expose
private Integer classNum;
@SerializedName("sectionInfos")
@Expose
private List<SectionInfo> sectionInfos = null;
任何人都可以告诉我如何解决这个问题。
已编辑:
使用for循环
后AllClassDataResp allClassDataResp = allClassDataRespList.get(position);
int classNumb = allClassDataResp.getClassNum();
List<SectionInfo> sectionInfoList = allClassDataResp.getSectionInfos();
String classAndSec = "";
for (SectionInfo sectionInfo : sectionInfoList)
{
String name = sectionInfo.getSectionName();
classAndSec = classNumb + "th" + " - " + name;
}
holder.tClassSec.setText(classAndSec);
答案 0 :(得分:0)
它会抛出IndexOutOfBoundsException
异常,因为您已经从列表中获取了对象。你有权访问它的子对象。
AllClassDataResp allClassDataResp = allClassDataRespList.get(position);
SectionInfo sectionInfo = list.get(position); // throwing IndexOutOfBounds Exception
您的列表可能无法包含足够的数据。您的列表大小小于您的位置,您将尝试获取那些不存在的值。
您可以获取列表值,如:
for(SectionInfo sectionInfo : list){
// your actual sectionInfo object get here.
}
答案 1 :(得分:0)
这里的问题是您的变量列表与变量allClassDataRespList的项目数不同。因此,您尝试访问非现有索引处的变量。
答案 2 :(得分:0)
您的代码allClassDataRespList.get(position)
正在访问超出可用范围的索引。假设您有以下数组
allClassDataRespList = new ArrayList<AllClassDataResp>();
allClassDataRespList.add(new AllClassDataResp(...) ); //index 0
allClassDataRespList.add(new AllClassDataResp(...) ); //index 1
allClassDataRespList.add(new AllClassDataResp(...) ); //index 2
现在假设您的函数可以访问列表中的对象
public AllClassDataResp getItem(int position)
{
return allClassDataRespList.get(position);
}
现在说明你得到的错误,让我们调用我们的函数
AllClassDataResp existing1 = getItem(0); //works fine
AllClassDataResp existing2 = getItem(1); //works fine
AllClassDataResp nonexisting = getItem(3); //throws IndexOutOfBoundsException
最常见的是检查数组大小是否确实存在索引存在
if(position < allClassDataRespList.size())
{
//exists
}
上查看有关该方法的更多信息
作为RecyclerView Adapater的onBindViewHolder
方法,我从未发现一个用例,其中给出了一个不存在的绑定项。您的Adapater的基本设计及其管理数据的方式一定存在问题