【问题标题】:IndexOutOfBoundsException: in RecyclerViewAdapterIndexOutOfBoundsException:在 RecyclerViewAdapter 中
【发布时间】:2016-09-17 04:48:28
【问题描述】:
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at com.ppl.adapter.FoodRecyclerViewAdapter.onBindViewHolder(FoodRecyclerViewAdapter.java:99)
at com.ppl.adapter.FoodRecyclerViewAdapter.onBindViewHolder(FoodRecyclerViewAdapter.java:24) 

什么错误?请解释我。食物有数据。 FoodCategory 也有数据。

在食物对象中;

private Integer id;
private String foodName;
// etc.
private List<FoodSize> foodSizes = new ArrayList<FoodSize>();

在 FoodSize 对象中;

private Integer price;
// etc

public Integer getPrice() {
        return price;
    }

在 FoodRecyclerViewAdapter 中;

List<Food> contents;    

public void onBindViewHolder(ItemViewHolder holder, int position);
    if (contents.get(position).getFoodSizes().get(0).getPrice() != null) {
                        holder.foodPrice.setText(contents.get(position).getFoodSizes().get(0).getPrice().toString());
                    }

这里;

[
 {
        "id": 1,
        "food_name": "Chicken",
            "food_category": { },
            "food_sizes": [
              {
                "id": 84,
                "size": "Normal",
                "food_id": 1,
                "price": 1100,
              }
            ]
  }
]

【问题讨论】:

  • 可能你在contents 中什么都没有。你确定你已经成功解析了你的JSON 吗?
  • 检查内容数组是否有值?
  • 哪些是第 99 行和第 24 行,顺便问一下,你在哪里初始化 contentsfoodSizes?请添加更多代码。 “这里”是什么意思,然后你发布 JSON?显示解析 JSON 的代码。
  • 在内容中。这里是api。 :D 我使用改造

标签: android arrays object


【解决方案1】:
 public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {

        FoodSize mfoodSize = (FoodSize)foodSizes.get(position);

        holder.foodPrice.setText(mfoodSize.getPrice().toString());

}

【讨论】:

  • 有什么区别?
  • 当您的列表已经是 FoodSize 类型时,为什么要将其转换为 FoodSize
【解决方案2】:

我认为您的问题出在getCount() 方法中:

像下面这样写:

@Override
public int getItemCount() {
    if (contents != null) return contents.size();
    return 0;
}

【讨论】:

    【解决方案3】:

    我明白了。

    if (contents.get(position).getFoodSizes().size() > 0) {
                        holder.foodPrice.setText(contents.get(position).getFoodSizes().get(0).getPrice().toString());
                    } else {
                        Log.i("Price 0", " 0");
                    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-21
      • 1970-01-01
      • 1970-01-01
      • 2019-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-08
      相关资源
      最近更新 更多