![](/img/trans.png)
[英]Launching BottomSheet from a RecyclerViewAdapter that extends with RecyclerView.Adapter inside onBindViewHolder
[英]how to extract a list from another list in OnBindViewHolder in RecyclerView.Adapter
@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。 我也嘗試使用Loop,但沒有用。
我的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);
它會引發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
}
作為onBindViewHolder
方法,我還沒有找到用例,其中沒有綁定的項。 您的Adapater基本設計及其如何管理數據一定有問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.