@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;
抛出索引越界异常。我也尝试使用 Loop,但没有奏效。
我的波乔班。
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);
它抛出IndexOutOfBoundsException
异常,因为您已经从列表中获取了对象。 您可以访问它的子对象。
AllClassDataResp allClassDataResp = allClassDataRespList.get(position);
SectionInfo sectionInfo = list.get(position); // throwing IndexOutOfBounds Exception
您的列表可能包含的数据不足。您的列表大小小于您的位置,并且您正在尝试获取那些不存在的值。
您可以获取如下列表值:
for(SectionInfo sectionInfo : list){
// your actual sectionInfo object get here.
}
这里的问题是你的变量列表的项目数与变量allClassDataRespList不同。因此,您正在尝试访问不存在索引处的变量。
您的代码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 AdapateronBindViewHolder
方法,我从未发现一个用例,其中给定了一个不存在的要绑定的项目。Adapater的基本设计以及它管理数据的方式一定有问题。