我试图通过改造从GET请求中获取List。但每当我尝试从response.body()(它成功从数据库中检索数据)的列表值中访问值时,错误始终是索引超出范围,List返回null。
我正在尝试使用List中的所有数据填充我的RecycleView。但它始终返回null,因此我的RecycleView始终为空。
以下是我的服务类的代码:
@GET("products/getallproducts") Call<List<Product>> getAllProducts();
检索我的List并填充RecycleView的类:
public class HomeActivity extends AppCompatActivity {
List<Product> proGet = new ArrayList<Product>();
//some more codes here
//some more codes here
//some more codes here
//lastly followed by the method createDummyData()
public void createDummyData() {
Call<List<Product>> call = restServices.getService().getAllProducts();
call.enqueue(new Callback<List<Product>>() {
@Override
public void onResponse(Call<List<Product>> call, Response<List<Product>> response) {
int statusCode = response.code();
productGet = response.body();
//^^^this is where the problem is
//class used for populating one section
SectionDataModel dm = new SectionDataModel();
dm.setHeaderTitle("trend");
//class SingleItemModel is for adding single item into the section
ArrayList<SingleItemModel> singleItem = new ArrayList<SingleItemModel>();
//adding each item into the SingleItem array list
singleItem.add(new SingleItemModel(proGet.get(0).status, productList.get(0).category));
singleItem.add(new SingleItemModel(proGet.get(0).name, productList.get(0).productid));
//populate the singleItem array list into one section
dm.setAllItemsInSection(singleItem);
//populate the whole RecycleView
allSampleData.add(dm);
}
@Override
public void onFailure(Call<List<Product>> call, Throwable t) {
}
});
}
`
logcat中的错误:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.kennethlo.kickgoo/com.example.kennethlo.kickgoo.HomeActivity}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
我绝望,并希望有人能够提供帮助。提前谢谢。
答案 0 :(得分:0)
首先需要检查您的响应大小是否大于0(零)。
if(productGet.size() > 0){
//Code...
}
并检查 productList 的大小是否大于0(零)。