IndexOutOfBoundsException:在RecyclerViewAdapter中

时间:2016-05-20 04:22:11

标签: android arrays object

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) 

有什么不对? Plz解释我。食物有数据。 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,
              }
            ]
  }
]

3 个答案:

答案 0 :(得分:0)

 public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {

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

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

}

答案 1 :(得分:0)

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

写得像吼叫:

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

答案 2 :(得分:0)

我明白了。

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